While taking interview for .NET Technologies i often ask about the execution sequence of the constructor and destructor in inheritance But from the my experience i have found that lots of people are still confused with execution sequence of constructor and destructors. Lets create a simple example and learn some basic things that is very important while using inheritance in C#.
- Constructors will be executed in from parent to child sequence means first parent class constructor will be executed then after that child class constructor will be executed.
- Destructors execution order is reverse then constructors first it will execute child class destructor and then it will execute the parent class destructor.
- Static constructors are different then the normal constructors and its executes when first object of class is created it will be executed. Most of people are very confused this kind of scenario in inheritance. Here scenario will be like when the first object of child class created then it will execute the child class static constructor and then after the parent class static constructor is executed. After that it will never got executed.
Lets create a simple class which will illustrate the above worlds. First lets create a class A with constructor,destructor and a static constructor.
public class A
{
static A()
{
System.Console.WriteLine("A Static Constructor");
}
public A()
{
System.Console.WriteLine("A public constructor");
}
~A()
{
System.Console.WriteLine("A Destructor");
}
}
public class B : A
{
static B()
{
System.Console.WriteLine("B Static Constructor");
}
public B()
{
System.Console.WriteLine("B public constructor");
}
~B()
{
System.Console.WriteLine("B Destructor");
}
}
class Program
{
static void Main(string[] args)
{
B b1 = new B();
B b2 = new B();
//code return to destroy object of a class
b1=b2 = null;
GC.Collect();
Console.ReadLine();
}
}
As you can see static constructors are only executed when the first object of a class is created and Constructors are executed like parent to child way and in reverse destructors are executed from child to parent way. Hope this will help you understand execution sequence of constructor in inheritance.