Order of Constructor and Destructor call in C# – Interview QA

Answer: the order of execution of constructor and destructor call in c# inheritance: The constructor call is from top to bottom i.e. from base class to the derive class. And the destructor call is in reverse order i.e. from bottom to the top.

C# code Example : Order of execution of Constructor and Destructor

//Base class
class Base
{
    public Base() { Console.WriteLine("Constructor: Base"); }
    ~Base() { Console.WriteLine("Destructor: Base"); }
}
//Derived class
class DerivedOne : Base
{
    public DerivedOne() { Console.WriteLine("Constructor: DerivedOne"); }
    ~DerivedOne() { Console.WriteLine("Destructor: DerivedOne"); }

}
//Derived class
class DerivedTwo : DerivedOne
{
    public DerivedTwo() { Console.WriteLine("Constructor: DerivedTwo"); }
    ~DerivedTwo() { Console.WriteLine("Destructor: DerivedTwo"); }
}


class Program
{
    static void Main(string[] args)
    {
        Base o = new DerivedTwo();
       
    }
}

Output:

Constructor: Base
Constructor: DerivedOne
Constructor: DerivedTwo
Destructor: DerivedTwo
Destructor: DerivedOne
Destructor: Base

Related Posts