Why is this an issue?
When a class has only a private constructor, it can’t be instantiated except within the class itself. Such classes can be considered
dead code and should be fixed
Exceptions
- Classes that access their private constructors (singletons or smart enums) are ignored.
- Classes containing only
staticmembers, nested types, or both are ignored. Classes with onlystaticmembers are covered by Rule S1118. - Classes that derive from SafeHandle since they can be instantiate through P/Invoke.
How to fix it
Code examples
Noncompliant code example
public class MyClass // Noncompliant: the class contains only private constructors
{
private MyClass() { ... }
}
Compliant solution
public class MyClass // Compliant: the class contains at least one non-private constructor
{
public MyClass() { ... }
}
Resources
Documentation
- S1118 - Utility classes should not have public constructors
- Microsoft Learn - SafeHandle Class
- Microsoft Learn - Platform Invoke (P/Invoke)
- Microsoft Learn - Use enumeration classes instead of enum types
- Wikipedia - Dead code
- Wikipedia - Singleton pattern
Articles & blog posts
- C# in Depth - Implementing the Singleton Pattern in C#
- Medium - Making enums smarter in C#