Why doesn’t the CLR always call value type constructors

The Microsoft C#4 Spec has changed slightly from previous versions and now more accurately reflects the behaviour that we’re seeing here:

11.3.10 Static constructors

Static constructors for structs follow
most of the same rules as for classes.
The execution of a static constructor
for a struct type is triggered by the
first of the following events to occur
within an application domain:

  • A static member of the struct type is referenced.
  • An explicitly declared constructor of the struct type is called.

The creation of default values
(ยง11.3.4) of struct types does not
trigger the static constructor. (An
example of this is the initial value
of elements in an array.)

The ECMA Spec and the Microsoft C#3 Spec both have an extra event in that list: “An instance member of the struct type is referenced”. So it looks as if C#3 was in contravention of its own spec here. The C#4 Spec has been brought into closer alignment with the actual behaviour of C#3 and 4.

EDIT…

After further investigation, it appears that pretty much all instance member access except direct field access will trigger the static constructor (at least in the current Microsoft implementations of C#3 and 4).

So the current implementations are more closely correlated with the rules given in the ECMA and C#3 specs than those in the C#4 spec: the C#3 rules are implemented correctly when accessing all instance members except fields; the C#4 rules are only implemented correctly for field access.

(The different specs are all in agreement — and apparently correctly implemented — when it comes to the rules relating to static member access and explicitly declared constructors.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)