Search code examples
c#constructorfieldprivate-members

Why do we need static private array to initialize other non static private array fields?


If you take a look inside Stack<T> class from .NET 4.0, you will notice that there is an "emptyArray" private static field which is used inside constructors to initialize a real "array" private field.

private T[] array;
private static T[] emptyArray;
private int size;
private int version;

static Stack()
{
    Stack<T>.emptyArray = new T[0];
}

public Stack()
{
    array = Stack<T>.emptyArray;
    size = 0;
    version = 0;
}

Why not just put this.array = new T[0]; ? And also why there are placed initialization strokes for size and version fields, if you omit those lines they will be initialied to default values (0) anyway.


Solution

  • That's because otherwise, every Stack gets his own instance of a new T[0]. Now they all refer to the same instance: the one that's declared static. Suppose you declare 1000 Stack<string>. These all have a reference to one string[0] object. If you declared the empty array inside the constructor, you would have a 1000 string[0] instances, one for each Stack<string>. So it's for performance reasons.

    The other initializers are unnecessary but if you take a look with Reflector through other source files, you see the same pattern everywhere: fields with default values are assigned explicit values inside a constructor.