I use the structure in the project, for example:
struct Position { public int X { get; private set; } public int Y { get; private set; }
I would like to add a method that allows me to create a modified copy of the structure with arbitrarily changed properties. For example, it would be convenient to use this:
var position = new Position(5, 7); var newPos = position.With(X: position.X + 1);
Is this a hacky idiom? Are there any better ways to support this?
public Position With(int? X = null, int? Y = null) { return new Position(X ?? this.X, Y ?? this.Y); }
Edit: in case this is unclear, the structure is immutable, I just want to create a new value with some changed values. By the way, this is very similar to Haskell's syntactic sugar for entries, where you can write newPos = oldPos { x = x oldPos + 1 } . This is a little experimental regarding whether such an idiom is useful in C #.
source share