C# 11 Features - Auto-Default Struct

Before understanding these new changes to Struct type, will do some understanding of the background of this implementation. At compile time, the compiler will attempt to take your code that initializes a given field and put it in a parameterless constructor. A constructor is essentially a function that is invoked when a structure is constructed.  

Structures implicitly derive from System.ValueType. The System.ValueType superclass implements a default constructor that subclasses cannot override. This means that it is not physically possible to explicitly define a parameter-less constructor in a structure. Because of this physical limitation the compiler imposes, it is not possible for the compiler to take your field initialization code and put it in the parameter-less constructor. However, you are allowed to specify one or more parameter constructors and you can initialize all the fields in it and a compile-time error will raise if fail to initialize all the fields.

The above story was prior to C# 10 and since C# 10, we are allowed to create the parameter-less constructor with some limitations I.e., it will raise a compiler error if fails to initialize all the declared fields as struct member fields must be definitely assigned when it's created because struct types directly store their data.

C# 11 Features – Auto-default Struct

In the previous image, you can see the compile-time error message on the same code block with different C# versions. In C# 8.0, we are not allowed to provide any parameter-less constructors and since C# 10, we are allowed to have a parameter-less constructor so that the user can have his own field initialization values while creating the struct type object.

But this is something tedious as you must for sure need to initialize all the fields or properties on the structure, if fails as in the above image you will see a compiler error accordingly.

Since C# 11, this restriction got viewed off and the compiler will do an additional job to add code to the constructor that initializes the missing fields or fields not initialized in the constructor while creating the object. 

C# 11 Features – Auto-default Struct

As we can see in the above image there are no compiler errors reported even Name field is not initialized in the constructor.

These are the new changes on structures since C# 11 to include auto-default fields in the constructor prior to executing it. 

Happy Coding πŸ˜Š


Similar Articles