skip to content

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.