DEV Community

Aman Singh Parihar
Aman Singh Parihar

Posted on

Sequence of object creation in .NET

We are going to learn some basics of how the object is created in c# .net, most importantly the sequence of how they are created when the classes are following inheritance.

This is very simple topic but confuses many developers, even I was confused when I first learnt this.

Lets try to understand this.

In this example we will take two classes "Parent" and "Child" to make things simple.

Below is the code for "Parent" class.

Here we can see that we have two constructor, default and parameterized.

Now lets see the code of child class. We will discuss two cases here.

Lets see 1st case:

Here is the code of "Child" class.

Now when we create the object of Child class, like this.

Child c = new Child();

Default constructor of the parent class will be called first, and then the child class constructor will be called.

Output of the above execution will be something like this.

image

Now lets see 2nd case:

Here we want to explicitly call the "Parent" class parameterized constructor.

For this we have to make some tweak in the "Child" class.

Here is the code of the Child class.

We can see that we have used a "base" keyword here, this will execute the parameterized constructor of the "Parent" class.

Now when we create the object of Child class, like this, by passing any number as a parameter.

Child c = new Child(1);

Parameterized constructor of "Parent" class will be executed first, then the constructor of the "Child" class.

Output of the code will be something like this.

image

Top comments (0)