Avoid uninstantiated internal classes
Avoid uninstantiated internal classes
Microsoft docsDescription
This rule tries to locate a call to one of the constructors of the type and reports a violation if no call is found.
The following types are not examined by this rule:
- Value types
- Abstract types
- Enumerations
- Delegates
- Compiler-emitted array types
- Types that can't be instantiated and that only define
staticmethods.
If you apply System.Runtime.CompilerServices.InternalsVisibleToAttribute to the assembly that's being analyzed, this rule doesn't flag types that are marked as internal (Friend in Visual Basic) by default, because a field may be used by a friend assembly. To analyze the assembly anyway, see Configure code to analyze.
Cause
An internal (assembly-level) type is never instantiated.
How to fix violations
To fix a violation of this rule, remove the type or add code that uses it. If the type contains only static methods, add the static modifier to the type to prevent the compiler from emitting a default public instance constructor.
Example
internal class MyClass
{
public void DoSomething()
{
}
}
public class MyGeneric<T> where T : new()
{
public T Create()
{
return new T();
}
}
MyGeneric<MyClass> mc = new MyGeneric<MyClass>();
mc.Create();When to suppress
It is safe to suppress a warning from this rule. We recommend that you suppress this warning in the following situations:
- The class is created through late-bound reflection methods such as System.Activator.CreateInstance.
- The class is registered in an inversion of control (IoC) container as part of the dependency injection pattern.
- The class is created automatically by the runtime or ASP.NET. Some examples of automatically created classes are those that implement System.Configuration.IConfigurationSectionHandler or System.Web.IHttpHandler.
- The class is used as a type parameter in a class definition and has a
newconstraint. The following example will be flagged by rule CA1812: