Quiz: Static fields initialization order

Here is a quiz for you:

What is the output of the following piece of code?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("A : {0}", Test.A);
        Console.WriteLine("B : {0}", Test.B);
    }
}

class Test
{
    public static int A = InitA();
    public static int B = A;

    static Test()
    {
        A = 10;
    }

    private static int InitA()
    {
        return B;
    }
}

Explanation

In the previous code we have a static constructor (Test) and two static fields (A and B).

1. Static constructor

A type can define only one static constructor. This constructor executes once per type and its execution is triggered by:

  • Instantiating the type
  • Accessing a static member of the type

2. Static fields

A type can define one or more static fields. The static fields are initialized before the static constructor executes, and they are initialized in the order in which they appear. If a type does not contain a static constructor, the static fields are initialized before the type will be used or “anytime earlier at the whim of the runtime. (This means that the presence of a static constructor may cause field initializers to execute later in the program than they would otherwise.)” [Albahari, C# 5.0 in a Nutshel, page 78].

So, as the result printed out is:

A : 10
B : 0
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s