Order Of Constructors Calling With Inheritance In C#

Constructor

Constructor is a special kind of method in a class with the same name of the class and without return type. 

We can have multiple constructors in a class (Parameterized Constructor/Copy Constructor/Static Constructor/Private Constructor). 

When we create a class without a constructor then, the compiler will automatically create a default constructor of the class.

Example

public class Animal
{
    public Animal()
    {
        Console.WriteLine("I am a constructor");
    }
}

Order of constructors calling with inheritance


With non-static constructors?

While object creation of a class, the default constructor of that class is automatically called to initialize the members of the class.

In case of inheritance if we create an object of child class then the parent class constructor will be called before child class constructor.

i.e. The constructor calling order will be top to bottom.

Example

public class Animal
{
    public Animal()
    {
        Console.WriteLine("I am animal constructor.");
    }
}
public class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("I am dog constructor.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        Console.Read();
    }
}

Output

Order Of Constructors Calling With Inheritance In C#

So as we can see in the output, the constructor of Animal class(Base class) is called before Dog class(Child).

But why?

Because when we inherit a class into another call then the child class can access all the features of the base class (except private members).

So if in the initialization process of child class there may be the use of parent class members.

This is why the constructor of the base class is called first to initialize all the inherited members.

With static constructors?

In the case of a static constructor, calling order will be reversed from non-static i.e. it will call from bottom to top.

Example

public class Animal
{
    static Animal()
    {
        Console.WriteLine("I am animal constructor.");
    }
}
public class Dog : Animal
{
    static Dog()
    {
        Console.WriteLine("I am dog constructor.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        Console.Read();
    }
}

Output

 

Here child class (Dog) constructor is called before the parent class (Animal) constructor.

Summary

In this article, we learned that in the case of non-static constructors, calling order is top to bottom, and with static constructors calling order is bottom to top.


Similar Articles