CA1812: Avoid uninstantiated internal classes

Value
Rule ID CA1812
Category Microsoft.Performance
Fix is breaking or non-breaking Non-breaking

Cause

An internal (assembly-level) type is never instantiated.

Rule description

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 cannot be instantiated and that only define static (Shared in Visual Basic) methods.

If you apply the System.Runtime.CompilerServices.InternalsVisibleToAttribute to the assembly that's being analyzed, this rule will not flag types that are marked as internal (Friend in Visual Basic) because a field may be used by a friend assembly.

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 one of the following to the type to prevent the compiler from emitting a default public instance constructor:

  • The static modifier for C# types that target .NET Framework 2.0 or later.

  • A private constructor for types that target .NET Framework versions 1.0 and 1.1.

When to suppress warnings

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 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 passed as a type parameter that has a new constraint. The following example will be flagged by rule CA1812:

    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();