Reputation: 643
Is there any way to force the static field initialization order in partial classes? Let's say in HelloWorld1.cs I have:
partial class HelloWorld
{
static readonly string[] a = new[] { "Hello World" };
}
Elsewhere in HelloWorld2.cs I have:
partial class HelloWorld
{
static readonly string b = a[0];
}
If a is initialized before b this is fine but if b is initialized before a then it throws an. The healthy way is probably to use a static constructor but I'm curious if there's a way to force or predict the initialization order when the fields classes are in different files of the same partial class.
Upvotes: 11
Views: 2578
Reputation: 18743
When the fields are present in the same file, the textual order defines the execution of their initialization:
10.5.5.1 Variable initializers - Static field initialization
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. If a static constructor (§10.12) 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.
However, in the case of fields declared in different files of partial classes, the order is undefined:
10.2.6 Partial types - Members
The ordering of members within a type is rarely significant to C# code, but may be significant when interfacing with other languages and environments. In these cases, the ordering of members within a type declared in multiple parts is undefined.
From the C# language specification.
Upvotes: 17
Reputation: 4203
From MSDN Documentation:
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. 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.
Upvotes: 1