Back to Basic – Calling base class constructor from derived class in C#

By | May 13, 2015

How to call base class constructor from derived class ?  Another frequently  asked question in interview for the beginners, and I have seen confusion around answering this. Let’s have a quick understanding on this. If we derive a class from a base class and want to pass data from the derived class constructor to the constructor of the base class, a derived class constructor is required to call the constructor from its base class. We use base keyword for this type of initialization.

Consider you have following BaseClass and a DerivedClass. Both of the class has one default and one parameterized constructor.

class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base Class Default Constructor");
}

public BaseClass(string value)
{
Console.WriteLine("Base Class Parameterized Constructor");
}
}

Here is the derive class.

class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("Derived Class Default Constructor");
}

public DerivedClass(string value)
{
Console.WriteLine("Derived Class Parameterized Constructor");
}
}

Following image shows a quick overview of the inheritance of these two classes.
image

Fig : Code Map View of both Derived and Base Class.
If you want to initialize through default constructor, you can just initialize the derived class object in the calling class.
So, here instantiate a Derived class the Main Calling method as shown below.

static void Main(string[] args)
{
DerivedClass derivedClass = new DerivedClass();
}

Here is the output which is very much expected, and the calling sequence too..
image
Following images shows the live debugging view of caller and calling class sequence between Main, Derived and Base Class

image image

Now, in the case of calling the Parameterized Constructor, you must use base keyword with the derived class constructor.  Calling without base keyword, it will call the default constructor of base.

static void Main(string[] args)
{
DerivedClass derivedClass = new DerivedClass("Parameter");
}

image

If you add base(value) with derived class constructor it will call the parameterized constructor only.

Main Method :

static void Main(string[] args)
{
DerivedClass derivedClass = new DerivedClass("Parameter");
}

Derived Class Parameterized constructor

public DerivedClass(string value) : base(value)
{
Console.WriteLine("Derived Class Parameterized Constructor");
}

Output :

image

Incase of you have multiple parameterized constructor, you need to pass the parameter as appropriate with base keyword.

image

Hope this will give you a fundamental understanding of the overall concept.

 

2 thoughts on “Back to Basic – Calling base class constructor from derived class in C#

  1. Pingback: Dew Drop – May 14, 2015 (#2014) | Morning Dew

  2. oby

    Thanks for your article, it was very useful to understand the code I’m working on.

Comments are closed.