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"); | |
} | |
} |
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"); | |
} | |
} |
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.
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"); | |
} | |
} |
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.
Top comments (0)