CSharp - Static constructors and field initialization order

Introduction

Static field initializers run before the static constructor is called.

If a type has no static constructor, field initializers will execute before the type is being used.

Static field initializers run in the order in which the fields are declared.

In the following code: X is initialized to 0 and Y is initialized to 3.

class Test
{
       public static int X = Y;    // 0
       public static int Y = 3;    // 3
}

If we swap the two field initializers around, both fields are initialized to 3. 

The next example prints 0 followed by 3 because the field initializer executes before X is initialized to 3.

Demo

using System;

class Program//from w  w w  . jav  a  2s . c  o  m
{
       static void Main() { 
          Console.WriteLine (Test.X);  // 3
       }   
}

class Test
{
       public static Test Instance = new Test();
       public static int X = 3;

       Test() { 
          Console.WriteLine (X); // 0
       }   
}

Result

If we swap the two lines in boldface, the example prints 3 followed by 3.