This has got me stumped. I was trying to optimize some tests for Noda Time, where we have some type initializer checking. I thought I\'d find out whether a type has
As I believe I've found some new interesting findings about the problem, I decided to add them as an answer, acknowledging at the same time that they are not addressing the "why it happens" in the original question. Maybe someone who knows more about the internal workings of the involved types might post an edifying answer based also on the observations I'm posting.
I've also managed to reproduce the issue on my machine and I've tracked a connection with the System.Runtime.InteropServices._Type Interface, which is implemented by the System.Type class.
Initially, I've found at least 3 workaround approaches for fixing the problem:
Simply by casting the Type to _Type inside the Main method:
var cctor = ((_Type)typeof(Test)).TypeInitializer;
Or making sure that approach 1 was used previously inside the method:
var warmUp = ((_Type)typeof(Test)).TypeInitializer;
var cctor = ((Type)typeof(Test)).TypeInitializer;
Or by adding a static field to the Test class and initializing it (with casting it to _Type):
static ConstructorInfo _dummy1 = (typeof(object) as _Type).TypeInitializer;
Later on, I discovered that if we don't want to involve the System.Runtime.InteropServices._Type interface in the workarounds, the problem doesn't occur either by:
Adding a static field to the Test class and initializing it (without casting it to _Type):
static ConstructorInfo _dummy2 = typeof(object).TypeInitializer;
Or by initializing the cctor variable itself as a static field of the class:
static ConstructorInfo cctor = typeof(Test).TypeInitializer;
I'm looking forward to your feedback.