Static field initialization and the Singleton pattern

A co-worker just asked me why the following code (I’ve “samplized” it) ended up with an array of correct size, but with null values:

private static SingletonClass singleton = new SingletonClass();

private static readonly string FIRST_VALUE = "First Value";
private static readonly string SECOND_VALUE = "Second Value";
private static readonly string THIRD_VALUE = "Third Value";

private ArrayList arrayList = new ArrayList();

private SingletonClass()
{
 arrayList.Add(FIRST_VALUE);
 arrayList.Add(SECOND_VALUE);
 arrayList.Add(THIRD_VALUE);

 string[] values = arrayList.ToArray(typeof(string)) as string[];
 // values.Length == 3
 // values[0], values[1], and values[2] are all null
}

public static SingletonClass Instance
{
 get { return singleton; }
}

The answer is found in the C# specification:

“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.”

The static instance of the singleton is being created before initializing the readonly strings. Thus, they were null! The solutions are either to create the object only when it is really asked for (super-lazy), or more simply to move the declaration of the SingletonClass instance to the bottom of the list of all declared static fields.

This entry was posted on Monday, July 10th, 2006 at 6:28 pm and is filed under programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.