5

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.

themaninthesuitcase
  • 4,771
  • 5
  • 25
  • 34

1 Answers1

9

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.

Ani
  • 111,048
  • 26
  • 262
  • 307