Quiz: More Type Constructors (Answer)

Well, I guess I will not purse my career as a radio game show host. Seems my quiz was not that hard. As most of you said, you change the class to a value type (class => struct). Ah, but the real fun is in the “why”.

Richard says, the .cctor emitted by the compiler is the same in regardless of whether it is on a class or a struct. So does the runtime treat structs special and just refuse to run their .cctors? Not exactly (at least not in this case), you will notice if you add a method to the type and call it the runtime will call the .cctor in either case.

Lawrence starts to get to heart of the issue and Stefan flushes it out even more. The C# compiler does not emit a call to the .ctor (or the instance constructor) of structs. This is because the default instance constructor (.ctor) is defined to simply put the value type in a zero state. Because the CLR makes that guarantee anyway, there is no need to actually run the .ctor for a value type. Notice this is not true for reference types, their .ctor’s must be run. So there difference is that for the value type the .ctor is not run and therefore the .cctor is not caused to run and for reference types the .ctor is run which causes the .cctor to run… wow, say that 5 times fast.