I\'m just getting curious about the following code :
public static class Container
{
public static readonly T[] EmptyArray = new T[0];
}
The guarantee is that the static field is initialized before you access it. (And also, if there is also a static constructor, then all static fields will be initialized before the static constructor is run.)
For generic classes, static initialization works on a per-type basis, so Container
acts as if it is a completely different class to Container
. This is actually true for all static parts of a generic class - each type gets its own 'copy'.
An example will show this last point more clearly:
static class Foo
{
static int count = 0;
public static int Increment()
{
return ++count;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine(Foo.Increment());
Console.WriteLine(Foo.Increment());
Console.WriteLine(Foo.Increment());
}
}
Output:
1
2
1