C# compiler error: “cannot have instance field initializers in structs”

In C#, a struct value is not a reference to an object in the way a value of a class type is. The value of a struct is the “union” of all the values of the instance fields of the struct.

Now, the default value of a struct type is the value where all those fields have their default values. Since the beginning of C#, the syntax:

new S()  // S is a value-type

where S is a struct type, has been equivalent to the default value of that struct. There is no constructor call! This is the exact same value which can (nowadays) also be written

default(S)  // S is a value-type

Now, things like

struct S
{
  int field = 42; // non-static field with initializer, disallowed!

  // ...
}

are illegal (cannot have instance field initializers in structs). They could give the impression that the field of a new S() would be 42, but in fact the field of new S() must be the default value of int (which is zero, distinct from 42).

With this explanation, you also see why it is not possible to create a non-static, zero-parameter constructor for a struct type, in C#.

Leave a Comment