DEV Community

Aman Singh Parihar
Aman Singh Parihar

Posted on

2 1

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.

public class Parent
{
private int id;
public Parent()
{
Console.WriteLine("Parent class default constructor");
}
public Parent(int id)
{
this.id = id;
Console.WriteLine("Parent class parameterized constructor");
}
}
view raw Parent.cs hosted with ❤ by GitHub

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.

public class Child:Parent
{
public Child()
{
Console.WriteLine("Child class contructor");
}
}
view raw Child-Case1.cs hosted with ❤ by GitHub

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.

public class Child : Parent
{
public Child(int id):base(id)
{
Console.WriteLine("Child class constructor");
}
}
view raw Child-Case2.cs hosted with ❤ by GitHub

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay