Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Few questions about constructors in C#

In C# regarding the inheritance of constructors:

  1. I have read that constructors cannot be inherited.
  2. If the base class contains a constructor, one or more, the derived class have to always call one of them? It is not possible that the derived class can skip the constructor of the base class?
  3. Derived class can have its own constructor but it has to call one of the base class constructors.

Are these statements corrects?

like image 380
JeffreyZ. Avatar asked Apr 04 '11 07:04

JeffreyZ.


2 Answers

  1. Yes, you're right, constructors are not inherited. So just because Object has a parameterless constructor, that doesn't mean that String has a parameterless constructor, for example. From section 1.6.7.1 of the C# 4 spec:

    Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.

  2. Yes, the constructor chain of a derived class constructor will always go through its base class constructor... although it may be indirectly, as it could chain to another constructor in the same class via this(...) instead of base(...). If you don't specify either this(...) or base(...), that's equivalent to base() - calling the parameterless constructor in the base class.

See my article on constructor chaining for more information.

like image 103
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet


1. You cannot inherit constructors, but you can chain constructors. Example:

public class DerivedClass : BaseClass {
  public DerivedClass(object arg):base(arg){}
}

2. Yes, for example, you cannot instantiate a class derived from an object with all private constructors (except in the particular scenario that Jon mentions below in his comment). You cannot skip the constructor of a base class, but you can have multiple overloads, and select the constructor you choose to use.

3. Yes, not sure what the question is here.

like image 37
smartcaveman Avatar answered Oct 13 '22 00:10

smartcaveman