So I started reading Jon Skeet’s 2nd edition of C# in depth and kind of confused about the following code in terms what it does and what is wrong with it (ch 13, section: Immutability and object initialization)
Message message = new Message(
"skeet@pobox.com",
"csharp-in-depth-readers@everywhere.com",
"I hope you like the second edition")
{
Subject = "A quick message" // <= {Subject = "A quick message" }; what is it?
};
Elaboration on this topic, would help tremendously!
Would someone explain that?
This code:
is equivalent to this:
That’s just object initializer syntax: see chapter 8 for more details.
The problems with this are:
of different overloads
With optional parameters and named arguments, all of this is solved:
It’s clear what means what, it’s all in a constructor call so the type can be immutable, you can have a single constructor with optional parameters (e.g. here we could have a
byte[] attachment = nullparameter specified in the constructor), and you can do all the validation in one place. Lovely.