0Pricing
C# Academy · Lesson

with Expressions on Records

Create modified copies of immutable objects.

The with Expression

A with expression creates a copy of a record with some properties changed, leaving the original untouched. It is the idiomatic way to "update" immutable records.

using System;

record Point(int X, int Y);

var a = new Point(1, 2);
var b = a with { Y = 9 };
Console.WriteLine(a + " | " + b); // Point { X = 1, Y = 2 } | Point { X = 1, Y = 9 }

Nondestructive Mutation

The original record is never modified. with performs a shallow copy and applies the listed changes to the copy only.

using System;

record User(string Name, int Age);

var original = new User("Ada", 30);
var older = original with { Age = 31 };
Console.WriteLine(original.Age + " " + older.Age); // 30 31

All lessons in this course

  1. init-Only Setters
  2. The required Modifier
  3. Immutable Object Patterns
  4. with Expressions on Records
← Back to C# Academy