CA1812: Avoid uninstantiated internal classes

TypeName

AvoidUninstantiatedInternalClasses

CheckId

CA1812

Category

Microsoft.Performance

Breaking Change

Non-breaking

Cause

An instance of an assembly-level type is not created by code in the assembly.

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 define static (Shared in Visual Basic) methods only.

If you apply System.Runtime.CompilerServices.InternalsVisibleToAttribute to the assembly that is being analyzed, this rule will not occur on any constructors that are marked as internal because you cannot tell whether a field is being used by another friend assembly.

Even though you cannot work around this limitation in Visual Studio Code Analysis, the external stand-alone FxCop will occur on internal constructors if every friend assembly is present in the analysis.

How to Fix Violations

To fix a violation of this rule, remove the type or add the 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:

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

  • The static (Shared in Visual Basic) modifier for types that target .NET Framework 2.0.

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 CreateInstance.

  • The class is created automatically by the runtime or ASP.NET. For example, classes that implement System.Configuration.IConfigurationSectionHandler or System.Web.IHttpHandler.

  • The class is passed as a generic type parameter that has a new constraint. For example, the following example will raise this rule.

    internal class MyClass
    {   
        public DoSomething()   
        {
        }
    } 
    public class MyGeneric<T> where T : new()
    {
        public T Create()
        {
            return new T();   
        }
    }
    // [...] 
    MyGeneric<MyClass> mc = new MyGeneric<MyClass>();
    mc.Create();
    

In these situations, we recommended you suppress this warning.

CA1811: Avoid uncalled private code

CA1801: Review unused parameters

CA1804: Remove unused locals