I'm curious of the C# spec says anything about the order of initializing static field's in C# 5 (.net4). For instance:
public class Test
{
public static readonly string A = "hi";
public static readonly string B = "bye";
public static readonly string DEFAULT = A;
}
In testing (Mono 2.x) they seem to be initialized in the order they appear in code. eg. As is, DEFAULT
will have the value "hi", but if I move the definition for DEFAULT
above A and B, it will be assigned NULL
because A hasn't been assigned yet.
Is there a guarantee that the variables are initialized in order? Or is it up to the compiler?
Thanks.
It is in the order that they appear in. See here.
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.
Also, when you have a static constructor:
If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With