Base constructor in C# - Which gets called first? [duplicate]

Solution 1:

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

Solution 2:

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");
  }
}