Order of static constructors/initializers in C#

See section 10.4 of the C# spec for the rules here:

when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.

So in other words, in your example ‘b’ is initialized to its default state (null) and so the reference to it in the initializer of ‘a’ is legal but would result in a NullReferenceException.

These rules are different to Java’s (see section 8.3.2.3 of the JLS for Java’s rules about forward references, which are more restrictive).

Leave a Comment