C# 10 makes it possible to declare a parameterless constructor and field initializers for a struct. Here is what happens when you declare field initializers but no explicit parameterless constructor, according to the language reference:
If you don't declare a parameterless constructor explicitly, a structure type provides a parameterless constructor whose behavior is as follows:
If a structure type has explicit instance constructors or has no field initializers, an implicit parameterless constructor produces the default value of a structure type, regardless of field initializers (…).
If a structure type has no explicit instance constructors and has field initializers, the compiler synthesizes a public parameterless constructor that performs the specified field initializations (…).
The following code outputs 1:
struct S {
public int X = 1;
}
class Program {
static void Main() { System.Console.WriteLine(new S().X); }
}
The following code outputs 0:
struct S {
public int X = 1;
public S(int x) { X = x; }
}
class Program {
static void Main() { System.Console.WriteLine(new S().X); }
}
This perfectly agrees with the spec cited above, but I find this illogical, so my question is: WHY? Why does the implicit parameterless constructor have different behavior depending on whether there are other instance constructors? Why cannot it always take field initializers into account, even if there are other instance constructors?