I am looking at this excellent article from Jon Skeet.

While executing the demo code, Jon Skeet says that we can expect three different kinds of behaviours. To quote that article:

The runtime could decide to run the type initializer on loading the assembly to start with... Or perhaps it will run it when the static method is first run... Or even wait until the field is first accessed...

When I try this out (on framework 4), I always get the first result. That is, the static method is initialized before the assembly is loaded. I have tried running this multiple times and get the same result. (I tried both the debug and release versions)

Why is this so? Am I missing something?

  • 1
    the exact behavior is implementation defined as in you can't rely on it happening in a specific way but the overall behavior is definied (static fields load before their first access) – ratchet freak Nov 30 '12 at 10:18
  • @ratchet, Hmm.. but is it always happening the first way. In about 10 tries... Hence I was confused. – TheSilverBullet Nov 30 '12 at 10:26
  • 8
    I mean that if you tried a completely different compiler/runtime (which still conforms to the standard) you can get a different result, retrying with the same framework will just get the same result unless they added some non-deterministic behavior (unlikely) – ratchet freak Nov 30 '12 at 10:39

When he says that "The results of running the above are quite varied.", he means that their potential results are varied. The act of running the exact same combination of compiler and runtime will almost certainly produce the same results every time. But other combinations (e.g., the Mono Project's C# compiler and runtime) would be perfectly within their rights to do one of the other things.

| improve this answer | |
  • Thanks for the clarification Ross. I was thinking that the same combination and different runs provide different results like the thread unsafe methods. To be sure I am clear, what Jon meant is that, since the specifications were ambigious, different compilers implement this differently. Am I right? – TheSilverBullet Dec 2 '12 at 2:45
  • Yes, that's what I meant. – Ross Patterson Dec 2 '12 at 13:25

Your Answer

