Static constructors and field initialization order - CSharp Custom Type

CSharp examples for Custom Type:Constructor

Introduction

Static field initializers run just before the static constructor is called.

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

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

The following example illustrates this-X is initialized to 0 and Y is initialized to 3:

Demo Code

using System;/*w w w  . ja  va 2s . c o m*/
class Foo
{
    public static int X = Y;    // 0
    public static int Y = 3;    // 3
}
class Program
{
    static void Main() { Console.WriteLine(Foo.X); }   // 3
}
class Foo1
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo1() { Console.WriteLine(X); }   // 0
}

Result


Related Tutorials