Base constructor in C# - Which gets called first?

Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code:

public class BaseClass {

    private string sentenceOne = null;  // A

    public BaseClass() {
        sentenceOne = "The quick brown fox";  // B
    }
}

public class SubClass : BaseClass {

    private string sentenceTwo = null; // C

    public SubClass() {
        sentenceTwo = "jumps over the lazy dog"; // D
    }
}

Order of execution is: C, A, B, D.

Check out these 2 msdn articles:

  • Why do initializers run in the opposite order as constructors? Part One
  • Why do initializers run in the opposite order as constructors? Part Two

The base constructor will be called first.

try it:

public class MyBase
{
  public MyBase()
  {
    Console.WriteLine("MyBase");
  }
}

public class MyDerived : MyBase
{
  public MyDerived():base()
  {
    Console.WriteLine("MyDerived");
  }
}

Don't try to remember it, try to explain to yourself what has to happen. Imagine that you have base class named Animal and a derived class named Dog. The derived class adds some functionality to the base class. Therefore when the constructor of the derived class is executed the base class instance must be available (so that you can add new functionality to it). That's why the constructors are executed from the base to derived but destructors are executed in the opposite way - first the derived destructors and then base destructors.

(This is simplified but it should help you to answer this question in the future without the need to actually memorizing this.)

Tags:

C#

.Net

Asp.Net