CSharp - Constructor and field initialization order in inheritance

Introduction

When an object is instantiated, initialization takes place in the following order:

From subclass to base class:

  • Fields are initialized.
  • Arguments to base-class constructor calls are evaluated.

From base class to subclass:

  • Constructor bodies execute.

The following code demonstrates:

class B
{
       int x = 1;         // Executes 3rd
       public B (int x)
       {
         ...              // Executes 4th
       }
}
class D : B
{
       int y = 1;         // Executes 1st
       public D (int x)
         : base (x + 1)   // Executes 2nd
       {
          ...             // Executes 5th
       }
}