Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable types with object initializer syntax

Tags:

c#

properties

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?

like image 672
user1899020 Avatar asked May 08 '16 21:05

user1899020


1 Answers

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

like image 73
Joe White Avatar answered Oct 15 '22 02:10

Joe White