How do you call a Base Class Constructor from Derived Class Constructor in .NET?During inheritance, constructors are not inherited. But .NET provides you an option to explicitly call a base class constructor from the derived class constructor using the keyword base.
This is demonstrated below with an example from C#: class baseClass
{ Output of this code will be: Member1 =
10, Member2 = 20 In this example, you have called the no-argument constructor and one-argument constructor of base class explicitly from the derived class constructor. Note that calling a base class constructor from derived class constructor will execute only the matching constructor of the immediate base class. It does not trigger matching constructors in all base classes of the derived class in the hierarchy. Consider the following example: class baseClass
{ Output of this code will be: Calling derivedClass1
constructor
You have
called the base class constructor from derivedClass2 using the keyword
base. It will trigger only its immediate base class derivedClass1 and
therefore you get the above shown output. If you want the next higher
level of base class named baseClass to be triggered, then you have to
modify the derivedClass1 constructor as shown below: Now you will get the following output if you execute the whole program: Passed the
following message to baseClass:Hello Also note that when you call a base class constructor, you have to ensure that the constructor with the specified signature already exists. If not, then you will end up in compilation error. This is demonstrated in the code shown below: class baseClass
{ In this example,
derivedClass1 constructor calls the baseClass constructor with one argument.
This doesnt exist in baseClass. Hence during compilation, you will
end up in the following error:
|