Immutable types with object initializer syntax
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.)
This is dated now, but with the release of C# 9 you can use init
to achieve the desired functionality.
So your example would become:
class Contract
{
// Read-only properties.
public string Name { get; init; }
public string Address { get; init; }
}
And then you could initialize with:
// success!
Contract a = new Contract { Name = "John", Address = "23 Tennis RD" };
But you would still be unable to modify the parameters after setting them (so effectively they are still readonly).
// error!
a.Name = "Uncle Bob";
Under the hood, when you use object initializer syntax prior to C# 9 the compiler would call the default constructor first, and then set the property values you've specified. Obviously if those properties are readonly (i.e. only a get
method), it can't set them. The init
only setter allows setting the value only on initialization, either via a constructor method or object initializer syntax.
More info is available here: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters