[ACCEPTED]-Initialization Order of Static Fields in Static Class-static-initializer

Accepted answer
Score: 64

Yes, they will, please see clause 16 of the C# specification:

The static field variable initializers 15 of a class correspond to a sequence of assignments 14 that are executed in the textual order in which 13 they appear in the class declaration (§ Within 12 a partial class, the meaning of "textual 11 order" is specified by § If 10 a static constructor (§15.12) exists in 9 the class, execution of the static field 8 initializers occurs immediately prior to executing 7 that static constructor. Otherwise, the 6 static field initializers are executed at 5 an implementation-dependent time prior to the 4 first use of a static field of that class.

That 3 being said I think it would be better to 2 do the initialization inside a static type 1 initializer (static constructor).

Score: 17

Hmm... I'm surprised that compiles (it does, I 10 checked). I'm not aware of any guarantee 9 that would make this safe. Use a static 8 constructor...

Edit: I accept (see better answer above) that 7 it will work; but my idea with code is to 6 keep it as simple and obvious as possible. If 5 it isn't obvious that it will work (and it can't 4 be if you have to ask), then don't write 3 it that way...

In particular, problems with 2 relying on field order:

  • it can break if you move code around (which I often do)
  • it can break if you split the code into partial classes

My advice remains: use 1 a static constructor for this scenario.

Score: 0

At first glance, I wouldn't be sure, and 3 I had to try this out to see if it even 2 compiled.

Given that, I would initialize 1 the value in a static constructor.

More Related questions