with expressions C# 9.0 allowed you to create a copy of a record with some properties changed. However, this was limited to record types.
C# 10.0 extends with expressions to work with all structs and anonymous types, making it easy to create modified copies without mutating the original.
Code
C#
var point = new Point { X = 1, Y = 2 };
var moved = point with { X = 5 };
var config = new { Host = "localhost", Port = 8080 };
var prodConfig = config with { Host = "prod.example.com" };C#
var point = new Point { X = 1, Y = 2 };
var moved = new Point { X = 5, Y = point.Y };
// No way to copy-and-modify anonymous types
var config = new { Host = "localhost", Port = 8080 };
var prodConfig = new { Host = "prod.example.com", Port = config.Port };Notes
- The
withexpression performs a shallow copy then applies the specified property changes - Especially useful with
readonlystructs where direct mutation is not possible - Anonymous types are always immutable so
withis the only way to derive a modified copy