CA1012: Abstract types should not have constructors

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

TypeName AbstractTypesShouldNotHaveConstructors
CheckId CA1012
Category Microsoft.Design
Breaking Change Non-breaking

Cause

A public type is abstract and has a public constructor.

Rule Description

Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has 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 Suppress Warnings

Do not suppress a warning from this rule. The abstract type has a public constructor.

Example

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

using System;
     
namespace Samples  
{   
    // Violates this rule      
    public abstract class Book      
    {          
        public Book()          
        {          
        }      
    } 
}
Imports System     

Namespace Samples
         
    ' Violates this rule      
    Public MustInherit Class Book 
            
        Public Sub New()          
        End Sub 
        
    End Class 
       
End Namespace 

Example

The following example fixes the previous violation by changing the accessibility of the constructor from public to protected.

using System;
     
namespace Samples  
{   
    // Violates this rule      
    public abstract class Book      
    {          
        protected Book()          
        {          
        }      
    } 
}
Imports System     

Namespace Samples
         
    ' Violates this rule      
    Public MustInherit Class Book 
            
        Protected Sub New()          
        End Sub 
        
    End Class 
       
End Namespace