Export (0) Print
Expand All
Expand Minimize

Abstract types should not have constructors







Breaking Change


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.

Community Additions

© 2014 Microsoft