Question

Consider the following class:

public class MyClass
{
    public static string[] SomeAmazingConsts = { Const1 };
    public static string Const1 = "Constant 1";
    public static string Const2 = "Constant 2";
}

Now, check out the usage:

class Program
{
    static void Main(string[] args)
    {
        string[] s = MyClass.SomeAmazingConsts;
        //s[0] == null
    }
}

The problem is that s[0] == null! How the heck does this happen? Now, reorder the static variable of MyClass as follows:

public class MyClass
{
    public static string Const1 = "Constant 1";
    public static string Const2 = "Constant 2";
    public static string[] SomeAmazingConsts = { Const1 };
}

Things start to work properly. Anyone can shed some light on this?

Was it helpful?

Solution

From 10.4.5.1 Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

So the initialization happens top to bottom, and in the first case Const1 has not been initialized, hence the null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top