C# `with` expression

From the description from Microsoft — available in C# 9.0 and later, a with expression produces a copy of its operand with the specified properties and fields modified.

The with expression is a nondestructive mutation that creates a new object with modified properties.

One important note is that in C# 9.0, a left-hand operand of a with expression must be of a record type. Beginning with C# 10, a left-hand operand of a with expression can also be of a structure type or an anonymous type.

Example

Let’s look at the following simple example

Animal record
Sample code

As expected, the output of it will be the following

Sample code output

Conclusion

For a full list of C# keyword, please take a look at C# Keywords

--

--