Home > Software engineering >  CS0171 A constructor in a struct must initialize all fields in the struct
CS0171 A constructor in a struct must initialize all fields in the struct

Time:08-15

struct Mutable {
    private int x;
    public Mutable() { }  //Compiler Error CS0171

}

So if i declare a constructor for a struct, It says that all the fields must be assigned but I am thinking why cant't the inline initializer just DEFAULT the field' values to their defaults?
I mean when no Constructor is specified the inline initializer does default the fields' values to their defaults.

CodePudding user response:

Actually it can, but it is planned for the next language version - C# 11. From the docs:

Auto-default struct

The C# 11 compiler ensures that all fields of a struct type are initialized to their default value as part of executing a constructor. This change means any field or auto property not initialized by a constructor is automatically initialized by the compiler. Structs where the constructor doesn't definitely assign all fields now compile, and any fields not explicitly initialized are set to their default value. You can read more about how this change affects struct initialization in the article on structs.

Read more:

  • Related