다음을 통해 공유


Abstract types should not have constructors

TypeName

AbstractTypesShouldNotHaveConstructors

CheckId

CA1012

Category

Microsoft.Design

Breaking Change

NonBreaking

Cause

A public type is abstract and has a public constructor.

Rule Description

Constructors on abstract types can only be called by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type with a public constructor is incorrectly designed.

How to Fix Violations

To fix a violation of this rule, either make the constructor protected, or do not declare the type as abstract.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example contains an abstract type that violates this rule, and an abstract type that is correctly implemented.

using System;

namespace DesignLibrary
{
   public abstract class BadAbstractClassWithConstructor
   {
      // Violates rule: AbstractTypesShouldNotHaveConstructors.
      public BadAbstractClassWithConstructor()
      {
      // Add constructor logic here.
      }
   }

   public abstract class GoodAbstractClassWithConstructor
   {
      protected GoodAbstractClassWithConstructor()
      {
         // Add constructor logic here.
      }
   }
}

The following example shows an abstract type that violates this rule.

In the example above abstract type has a public constructor, which can confuse users. They see the public constructor, but do not understand why they are unable to create the type.

The following example fixes the above violation by changing the constructor's accessibility from public to protected.