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.
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 .
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.
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.
A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With