Constructor and Destructor execution sequence with inheritance

In this article I will explain about the execution sequence of the constructor and destructor in inheritance in C#.
  • 5639

Introduction

Inheritance is the important concept in C#. During Inheritance base class and derived class may also contain constructor and destructor. 
In this case it is little confusing That base class constructor will be called first or Derived class. If we create an instance for the derived class then constructor of base class will be called first and when derived instance is destroyed then base destructor will also be invoked .

Base class constructor will be called first. Then

The order of execution of constructors will be in the same order as their derivation.
The order of execution of destructors will be in reverse order of their derivation.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ProgramCall

{

    class Base1

    {

        public Base1()

        {

            Console.WriteLine("It is Base  Class  Constructor");

        }

        ~Base1()

        {

            Console.WriteLine("It is Base  Class  Destructor");

        }

    }

    class Derived1 : Base1

    {

       public Derived1()

        {

 

            Console.WriteLine("It is Derived  Class  Constructor");

        }

        ~Derived1()

        {

            Console.WriteLine("It is Derived  Class  Destructor");

        }

    }

    class ConstructorInheritance

    {

        static void create()

        {

            Derived1 obj = new Derived1();

        }

        static void Main()

        {

            create();

            GC.Collect();

            Console.Read();

        }

    }

 

The output of following program

Clipboard174.jpg 

© 2020 DotNetHeaven. All rights reserved.