Initializing Static Fields

I'm just curious about the following code:

public static class Container<T> { public static readonly T[] EmptyArray = new T[0]; } 

As I understand it, the static class Container will be initialized when the following code is executed:

 ... var emptyArray = Container<int>.EmptyArray; ... 

I'm right? Any explanations for initializing static generic classes / members would be appreciated. Thanks in advance.

+4
source share
2 answers

It is guaranteed that the static field is initialized before you receive it. (And also, if there is also a static constructor, then all static fields will be initialized before the static constructor starts.)

For generic classes, static initialization works on the basis of each type, so the Container<int> acts as if it were a completely different class for the Container<double> . This is really true for all the static parts of the universal class - each type gets its own "copy".

An example will show this last point more clearly:

 static class Foo<T> { static int count = 0; public static int Increment() { return ++count; } } public class Program { public static void Main() { Console.WriteLine(Foo<int>.Increment()); Console.WriteLine(Foo<int>.Increment()); Console.WriteLine(Foo<double>.Increment()); } } 

Output:

 1 2 1 
+7
source

Initializers of a static field really move to the static constructor (type initializer) of the class. Thus, your code compiles automatically:

 public static class Container<T> { public static readonly T[] EmptyArray; static Container() { EmptyArray = new T[]; } } 

From MSDN on static constructors:

It [Static constructor] is called automatically before the creation of the first instance or reference to any static elements.

Since Container<string> and Container<bool> do not match, the static constructor is called once for each type T

+3
source

All Articles