Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FxCop Abstract types should not have constructors when no new

I have an issue with FxCop and the warning: Abstract types should not have constructors.

This is being displayed for a number of abstract classes (possibly all, I haven't checked). When I look most of them have no new method so I assume it's the complier adding a default one. So to remove it I add a private default constuctor (Private Sub New()), this then means all the inherting classes fail to build with the error: Class 'InheritingClass' has no accessible 'Sub New' and cannot be inherited.

This seems odd as FxCop requests no public constructor, but when I remove it the build fails.

like image 956
themaninthesuitcase Avatar asked Nov 26 '10 11:11

themaninthesuitcase


People also ask

Should abstract class constructor be protected?

After all, an abstract class cannot be created directly – only via a derived instance. Consequently, it is only the derived classes for whom it makes sense to access the constructor in the first place. Hence, ReSharper recommends that you make the constructor protected .

Should abstract class have public constructor?

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.

Can abstract class have constructor in C#?

Answer: Yes, an abstract class can have a constructor. In general, a class constructor is used to initialize fields. Along the same lines, an abstract class constructor is used to initialize fields of the abstract class.

What is protected constructor in C#?

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor.


1 Answers

Try adding a protected, parameterless constructor to the abstract class instead.

When you don't provide a constructor, the compiler adds a public, parameterless one for you. Clearly, it isn't appropriate for an abstract class to have public constructors since they are effectively protected anyway - constructors on abstract types can at best be called by subclasses (that's the whole point of an abstract type - it can't be instantiated 'vanilla'). This design flaw is what causes FxCop to complain.

On the other hand, the step you took to fix the issue was too extreme; classes (abstract or not) that have only private constructors are not subclassable in practice (except by a nested class) - there is no implicit or explicit base(...) constructor-call that could possibly work in a derived class's constructor.

EDIT: I like the way this MSDN page puts it:

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.

like image 53
Ani Avatar answered Nov 15 '22 05:11

Ani