Beachwalker Beachwalker - 1 year ago 158
C# Question

Change property of immutable type

I have stored immutable types in a temporary CQRS read store (query/read side, in fact implemented by a simple List with abstraction access layer, I don't want to use a full blown document database at this point). These read stores contains items like the following:

public class SomeItem
private readonly string name;
private readonly string description;

public SomeItem(string name, string description)
{ = name;
this.description = description;

public string Name
get { return; }

public string Description
get { return this.description; }

Now I want to change the Name and in a 2nd Command the Description.
These changes should keep the current state, which means for the example above:

// initial state
var someItem = new SomeItem("name", "description");

// update name -> newName
someItem = new SomeItem("newName", someItem.Description);

// update description -> newDescription
someItem = new SomeItem(someItem.Name, "newDescription");

This does look error prone to me if you have several properties... you have to manage keeping the current state. I could add something like Clone() to every type but I think/hope there is something better out there that performs well and is easy to use, I don't want to write much repetive code (lazy programmer). Any suggestions how to improve the code above? The SomeItem class needs to stay immutable (transported through several different threads).

Answer Source

What you are looking for is commonly called the with operator:

// returns a new immutable object with just the single property changed
someItem = { someItem with Name = "newName" };

Unfortunately, unlike F#, C# does not have such an operator (yet?).

Other C# developers are missing this feature as well, which is why someone wrote a Fody extension to do exactly that:

Here's another approach, which implements an UpdateWith method manually but requires a few helper objects. Luaan's answer describes this approach in more detail:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download