views:

215

answers:

3

If a public constructor in an abstract class can only be called by their derived classes it should be functionally equivalent to a protected constructor. Right?

Is there any difference in declaring a public constructor, instead of a protected one, in an abstract class? What would you use it for? Why the compiler doesn't complaint?

Thanks

+6  A: 

Absolutely correct. You should favor the protected constructor.

EDIT: no the compiler doesn't complain, but tools like FxCop (& Code Analysis) do. I believe there are some weird reflection tricks you can do with public constructors on abstract classes, but from a standpoint where you are merely providing base class functionality to other developers writing subclasses, stick with the protected constructor.

Jesse C. Slicer
+1  A: 

Yes, you are right, practically public constructor has no use in abscract class as you cant create them.

However compiler will not complain because that way there are so many useless things you can write in context of c#, but it will not be able to check its logical meaning, it can only check the parsing rules which it is set for.

And sure c# creators have focused on creating compilation grammar (rules) that are actual harmful and violating the language use.

Akash Kava
+1  A: 

You are correct. A public constructor in an abstract class is functionally equivalent to a protected constructor.

I prefer to use a protected constructor in this case.

While, it is true that the compiler will not complain about you doing this, the compiler will complain about trying to generate an instance of the abstract class. Visual Studio is smart enough, as well, to not provide Intellisense if you try to instantiate the abstract class.

Reed Copsey
There are some edge cases with reflection that can be simplified by making abstract class constructors public ... but they're exceptionally rare. I generally agree that constructors in abstract classes should be protected (or private if they are invoked by other constructor overloads).
LBushkin