2
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.

3
  • 1
    Traditionally, you could not create a default constructor for a struct. Now you can, but with the restriction that you must do the work that compiler did for you before (by initializing everything) learn.microsoft.com/en-us/dotnet/csharp/language-reference/…. Also, you should read up on why mutable structs are a bad idea. Commented Aug 14, 2022 at 20:58
  • Can you please edit post to clarify what you want to figure out? So far it reads "I don't like C# designers' choices" which is purely opinion based... Commented Aug 14, 2022 at 21:06
  • Does this answer your question? C# struct default values Commented Aug 14, 2022 at 21:18

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Okay thank you but Why woudn't they do this much earlier, like in classes?
'Cause (that's the whole answer). Really, you are asking a question like "why doesn't Hyundai sell a covertible?"
Okay, got It, I am sorry.
@EricMovsessian reasons can be plentiful - didn't think of (very doubtful though), considered to be better to be better option, considered to low impact feature to implement in that language version release time window, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.