For example, I have an immutable type
class Contact
{
// Read-only properties.
public string Name { get; }
public string Address { get; }
}
And I hope I can use object initializer syntax to create a Contact
Contact a = new Contact { Name = "John", Address = "23 Tennis RD" };
But I cannot. Any possible way to make use of the powerful object initializer syntax in this case?
The closest thing would be a constructor with optional parameters:
class Contact
{
public string Name { get; }
public string Address { get; }
public Contact(string name = null, string address = null) {
Name = name;
Address = address;
}
}
Then you can call it with parameter names:
new Contact(
name: "John",
address: "23 Tennis RD"
)
The syntax is slightly different from an object initializer, but it's just as readable; and IMO, the difference is a good thing, because constructor parameters tend to suggest immutable properties. And you can specify the parameters in any order, or leave some out, so it's just as powerful as object initializer syntax.
This does require some extra code (defining the constructor, assigning all the properties), so it's more work than object initializer syntax. But not too terrible, and the value of immutable objects is worth it.
(For what it's worth, C# 7 may get immutable "record types" that have much simpler syntax. These may or may not make it into the final release, but they sound pretty cool.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With