Reputation: 77329
given the following code:
public static class Helpers
{
private static Char[] myChars = new Char[] {'a', 'b'};
private static Int32 myCharsSize = myChars.Length;
}
Is it guaranteed that myChars
will be initialized before I use its length to assign to myCharsSize
?
Upvotes: 62
Views: 8200
Reputation: 351476
Yes, they will, please see clause 15.5.6.2 of the C# specification:
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 (§15.5.6.1). Within a partial class, the meaning of "textual order" is specified by §15.5.6.1. If a static constructor (§15.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.
That being said I think it would be better to do the initialization inside a static type initializer (static constructor).
Upvotes: 74
Reputation: 1062620
Hmm... I'm surprised that compiles (it does, I checked). I'm not aware of any guarantee that would make this safe. Use a static constructor...
Edit: I accept (see better answer above) that it will work; but my idea with code is to keep it as simple and obvious as possible. If it isn't obvious that it will work (and it can't be if you have to ask), then don't write it that way...
In particular, problems with relying on field order:
partial
classesMy advice remains: use a static constructor for this scenario.
Upvotes: 18
Reputation: 12401
At first glance, I wouldn't be sure, and I had to try this out to see if it even compiled.
Given that, I would initialize the value in a static constructor.
Upvotes: 0