Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static field initialization order with partial classes

Tags:

c#

.net

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.

like image 854
Alton XL Avatar asked Mar 16 '15 21:03

Alton XL


Video Answer


1 Answers

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.

like image 143
Otiel Avatar answered Oct 11 '22 11:10

Otiel