skip to content

Nondestructive Mutation

A with expression copies a record shallowly and changes chosen properties, so a nested list stays shared. Interviewers ask what is copied and what is not.

on this pageshow

explore

questions

6

In C#, what does settings with { TenantId = "alpha" } return when settings is a record, and does settings change?

level: juniorimportance: must knowfreq 72%

answer

  1. nondestructive, not in place
  2. a new instance every time
  3. every other member carried over
  4. records, structs, anonymous types only

basics

~20 s

A with expression returns a new record of the same run-time type, with every member copied from settings and only TenantId replaced. The original settings object is not modified; both variables now refer to different objects.

solid answer

~40 s

A `with` expression performs **nondestructive mutation**: it copies the receiver and then assigns the members listed in the braces on the copy. So `settings with { TenantId = "alpha" }` returns a new record whose other properties hold the same values as `settings`, while `settings` itself is untouched and `ReferenceEquals(copy, settings)` is `false`. The listed members must be fields or properties the call site can set, through a `set` or an `init` accessor; a get-only property is rejected with CS0200. The receiver must be a record, or since C# 10 a struct or an anonymous type; an ordinary class is rejected with CS8858.

code

csharp · 10 lines
csharp
var baseline = new TenantSettings("default", 30, "eu-west");
var alpha = baseline with { TenantId = "alpha" };
var slow = alpha with { TimeoutSeconds = 120 };

Console.WriteLine(baseline);
Console.WriteLine(alpha);
Console.WriteLine(slow);
Console.WriteLine(ReferenceEquals(alpha, baseline));

record TenantSettings(string TenantId, int TimeoutSeconds, string Region);

go deeper

for a junior

Recall that with returns a new instance, copies every member, replaces only the ones you list, and never touches the original.

for a middle

Explain which members may appear in the braces (set or init accessors, mutable fields) and which receivers are allowed, naming CS0200 and CS8858.

for a senior

Point out at once that the copy is shallow and that the result keeps the receiver's run-time type, the two facts that bite in production.

for a principal

Frame with as the reason records can be init-only without making every variant a full constructor call, so adding a member does not ripple through call sites.

## What a `with` expression is A **`with` expression** is C#'s syntax for producing a modified copy of a value without touching the original. It was added with records in C# 9 and widened to structs and anonymous types in C# 10. The shape is a receiver expression, the `with` keyword, and a brace list that looks like an object initializer: ```csharp var baseline = new TenantSettings("default", 30, "eu-west"); var alpha = baseline with { TenantId = "alpha" }; Console.WriteLine(baseline); // TenantId = default Console.WriteLine(alpha); // TenantId = alpha, TimeoutSeconds = 30, Region = eu-west Console.WriteLine(ReferenceEquals(alpha, baseline)); // False record TenantSettings(string TenantId, int TimeoutSeconds, string Region); ``` The documentation calls this **nondestructive mutation**: the result looks like an edited `baseline`, but `baseline` is never edited. ## What you get back 1. **A new instance.** For a record class the expression allocates a new object; the variable on the left of the assignment refers to it, and the receiver keeps referring to the old one. 2. **Every member copied.** Members you do not list keep the receiver's values — `TimeoutSeconds` is still `30` and `Region` is still `"eu-west"` above. 3. **Listed members replaced.** Each `Name = value` pair in the braces is assigned on the copy, in the order written. 4. **The same run-time type.** If the receiver is an instance of a derived record, the copy is an instance of that derived record too. The receiver is not modified in any way, so code that still holds `baseline` keeps seeing the old values. That is the whole point: a settings object handed to another component cannot be changed under it by the component that derived a variant from it. ## What the braces may contain The brace list is not free-form. Each entry must name an **accessible instance field or property** of the receiver's type, and that member must be assignable at the call site: - a property with a `set` accessor, or with an `init` accessor — positional record parameters produce `init` properties, which is why `with` is the normal way to "change" them; - a mutable field; - **not** a property with only a `get` accessor — the compiler reports CS0200, "Property or indexer 'TenantSettings.CacheKey' cannot be assigned to -- it is read only"; - **not** a member of a derived type that the receiver's compile-time type does not declare. An empty list, `baseline with { }`, is legal and simply produces a copy. ## Which receivers are allowed | Receiver | Allowed since | What the copy is | |---|---|---| | `record` / `record class` | C# 9 | a new object made through the record's copy constructor | | `record struct`, any `struct`, tuples | C# 10 | a value copy of the struct | | anonymous type | C# 10 | a new instance of the same anonymous type | | ordinary `class` | never | compile error CS8858 | For an ordinary class the compiler says "The receiver type 'Plain' is not a valid record type and is not a struct type." A class has no compiler-generated copying member, so there is nothing for `with` to call. ## Why it matters in practice Records are usually declared with `init`-only properties, so after construction their properties cannot be assigned. Without `with`, deriving a variant would mean calling the constructor again and repeating every argument, which breaks every time a property is added. `with` copies everything and lets you name only what differs, so adding a property to the record does not touch the call sites. Two cautions belong in the first answer you give: - **The copy is shallow.** A member that holds a reference — a `List<string>`, an array, another class — is copied as a reference, so both records then point to the same object. - **It is an expression.** Its value has to go somewhere: into a variable, a return, an argument. Equality between the copy and the original is a separate subject, covered with record classes; what matters here is that the copy is a different object with the listed members replaced.

  • In C#, can a with expression change a property that only has a get accessor?
    No. Each member in the braces must be assignable at the call site through a `set` or `init` accessor, or be a mutable field. A get-only property is rejected with CS0200, "cannot be assigned to -- it is read only". Positional record parameters generate `init` properties, so those can always be listed.
  • In C#, why can you not use with on an ordinary class?
    Because the compiler has nothing to copy it with. A record class gets a synthesized copy constructor and a hidden clone method; a struct is copied by value; an anonymous type is compiler-generated. An ordinary class has none of these, so the compiler reports CS8858: the receiver type is not a valid record type and is not a struct type.
  • In C#, does settings with { } do anything useful?
    Yes: an empty brace list is legal and returns a copy of `settings` with every member carried over. For a record class that is a new object, so `ReferenceEquals` with the original is `false`, although the members it holds are the same values and references.

  • A with expression edits the original record in place.
  • Members not listed in the braces are reset to their default values.
  • with works on any class that has settable properties.
  • with bypasses accessors, so it can set a get-only property.
  • The copy and the original are the same object with a new value.
open as a page

In C#, why does adding a tag to one tenant's settings record, copied from a baseline with with, change every tenant's Tags list?

level: middleimportance: must knowfreq 62%

basics

~10 s

A with copy copies each field, and a List<string> field holds a reference, so every copy shares one list. Give the copy its own list in the with, or use an immutable collection type.

open as a page

In C#, what code does the compiler generate for a with expression on a record class, and why may it assign init-only properties?

level: middleimportance: should knowfreq 40%

basics

~20 s

The compiler calls the record's hidden clone method, which runs the copy constructor to copy every field, then assigns the listed members on the new copy. Those assignments count as part of initializing the copy, so init accessors are allowed.

open as a page

Since C# 10, how does a with expression behave on a plain struct, a tuple or an anonymous type, compared with a record class?

level: middleimportance: should knowfreq 30%

basics

~20 s

On a struct or tuple, with copies the value and then assigns the listed members, with no copy constructor to customize. On an anonymous type it builds a new instance of the same type. Both need C# 10.

open as a page

In C#, a method takes a TenantSettings record and returns settings with { TimeoutSeconds = 60 }; passed an EnterpriseSettings derived record, what does it return, and what can it change?

level: seniorimportance: should knowfreq 32%

basics

~20 s

It returns an EnterpriseSettings with every derived member, such as Region, copied and TimeoutSeconds set to 60, because the hidden clone method is virtual. The braces may only name members of the compile-time type TenantSettings.

open as a page

In C#, what must a hand-written copy constructor on a record class do so that every with expression deep-copies its Tags list correctly?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Declare protected TenantSettings(TenantSettings original) (private if sealed), chain to the base copy constructor, clone the list, and assign every other member yourself, because the compiler no longer generates the field-by-field copy.

open as a page