Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the utility of public constructors in abstract classes in C#?

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?

like image 975
Julio César Avatar asked Nov 05 '09 17:11

Julio César


People also ask

What is the use of constructor in abstract class?

A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class.

Can we have public constructor in abstract class?

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.

What is the use of constructor in abstract class in C#?

If so what is the use? 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.

Should constructor of abstract class be protected?

An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public.


2 Answers

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.

like image 72
Jesse C. Slicer Avatar answered Oct 05 '22 23:10

Jesse C. Slicer


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.

like image 33
Reed Copsey Avatar answered Oct 06 '22 00:10

Reed Copsey