C# – Why Does This Static Field Always Get Initialized Over-Eagerly?

cinitializationlazy-initializationstatic-access

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?

Best Answer

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.

Related Topic