Constructor and field initialization order - CSharp Custom Type

CSharp examples for Custom Type:Constructor

Introduction

We saw previously that fields can be initialized with default values in their declaration:

class Player
{
  int shields = 50;   // Initialized first
  int health = 100;   // Initialized second
}

Field initializations occur before the constructor is executed and in the declaration order of the fields.


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

Related Tutorials