The initialization order of static fields in a static class

given the following code:

public static class Helpers { private static Char[] myChars = new Char[] {'a', 'b'}; private static Int32 myCharsSize = myChars.Length; } 

Is myChars initialization myChars before I use its length to assign myCharsSize ?

+38
c # static-initializer
Sep 29 '09 at 20:25
source share
3 answers

Yes, they will, see 10.4.5.1 Initialization of a static field :

The initializers of a static variable of a class field correspond to a sequence of assignments executed in the text order in which they appear class declaration. If a static constructor (section 10.11) exists in the class, execute the static field initializers before executing this static constructor. Otherwise, static field initializers are executed for a time, depending on the implementation, until the first use of the static field in this class.

Saying, I think it would be better to do initialization inside a static type initializer (static constructor).

+42
Sep 29 '09 at 20:27
source share
— -

Hmm ... I'm surprised that compiles (this, I checked). I do not know any guarantees that will make it safe. Use a static constructor ...




Edit: I accept (see best answer above ) that it will work; but my idea with the code is to make it as simple and obvious as possible. If it is not obvious that it will work (and cannot be, if you need to ask), then do not write it this way ...

In particular, problems related to field order:

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

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

+11
Sep 29 '09 at 20:27
source share

At first glance, I would not be sure, and I had to try this to make sure that it was even compiled.

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

0
Sep 29 '09 at 20:29
source share



All Articles