How to add using the 'with' keyword?

Viewed 125
public record Cube(int x, int y, int z, int w);

I recently ran across a time I was doing this:

var next = new Cube(existing.x + 1, existing.y, existing.z, existing.w);

and I thought there must be a cleaner way to add arbitrary values to the record. But when I try this:

var next = existing with { x = x+1 };

It cries because you do not have access to the values to add to. Instead I have to do this:

var next = existing with { x = existing.x+1 };

Am I just wanting too much from the with keyword?

2 Answers

The x in x = x+1 is the x of the next instance to be created. However, this instance does not yet exist at that point that's why the compiler complains. Instead, you have to state explicitly that the second x is the one of the existing instance.

Related