Export (0) Print
Expand All
Expand Minimize
10 out of 12 rated this helpful - Rate this topic

Abstract types should not have constructors

TypeName

AbstractTypesShouldNotHaveConstructors

CheckId

CA1012

Category

Microsoft.Design

Breaking Change

NonBreaking

A public type is abstract and has a public constructor.

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.

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

Do not exclude a warning from this rule.

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.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.