Udostępnij za pośrednictwem


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 within the assembly.

Rule Description

This rule tries to locate a call to one of the type's constructors, 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 define static (Shared in Visual Basic) methods only.

If you apply System.Runtime.CompilerServices.InternalsVisibleToAttribute to the assembly being analyzed, this rule will not fire on any constructors marked as internal because you cannot tell if 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 fire 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 targeting .NET Framework versions 1.0 and 1.1.

  • The static (Shared in Visual Basic) modifier for types targeting .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 with a new constraint. For example, the following example will fire 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.

Avoid uncalled private code

Review unused parameters

Remove unused locals