With expression
with
expression produces a copy of its operand with the specified properties and fields modified
- You use object initializer syntax to specify what members to modify and their new values.
- C# 10 supports with expressions for all structs, including record structs, as well as for anonymous types.
- In the case of a reference-type member, only the reference to a member instance is copied when an operand is copied. Both the copy and original operand have access to the same reference-type instance.
public struct Point
{
public Point(double x, double y) {
X = x;
Y = y;
}
public double X { get; init; }
public double Y { get; init; }
public override string ToString() => $"({X}, {Y})";
}
//struct type
var p1 = new Point(10, 10);
var p2 = p1 with { Y = 12 };
Console.WriteLine(p1);
Console.WriteLine(p2);
//anonymous type
var a1 = new { X = 10, Y = 10} ;
var a2 = a1 with {X = 12 };
Console.WriteLine(a1);
Console.WriteLine(a2);
Example