skip to content

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%

answer

  1. copy of a reference, not of the list
  2. synthesized copy constructor copies fields
  3. init stops reassignment only
  4. give each copy its own list

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.

solid answer

~40 s

The record's synthesized copy constructor copies every instance field by value, and the value of a `List<string>` field is a **reference**. So `baseline with { TenantId = "alpha" }` produces a new record whose `Tags` property refers to the very same list as `baseline.Tags`, and `alpha.Tags.Add(...)` is visible through every record copied from that baseline. The `init` accessor does not help: it stops the property being reassigned after initialization, not the list being mutated. Fixes: give each copy its own list in the expression (`baseline with { TenantId = "alpha", Tags = [.. baseline.Tags] }`), store tags in an immutable collection type so no copy can mutate them, or write a copy constructor that clones the list.

code

csharp · 17 lines
csharp
var baseline = new TenantSettings("default", 30, new List<string> { "beta" });

var alpha = baseline with { TenantId = "alpha" };
var bravo = baseline with { TenantId = "bravo", TimeoutSeconds = 60 };

alpha.Tags.Add("priority-support");

Console.WriteLine(string.Join(",", bravo.Tags));
Console.WriteLine(ReferenceEquals(alpha.Tags, baseline.Tags));

var charlie = baseline with { TenantId = "charlie", Tags = [.. baseline.Tags] };
charlie.Tags.Add("trial");

Console.WriteLine(string.Join(",", baseline.Tags));
Console.WriteLine(string.Join(",", charlie.Tags));

record TenantSettings(string TenantId, int TimeoutSeconds, List<string> Tags);

go deeper

for a junior

Remember that a with copy shares any list or array the record holds, so changing that collection through one copy shows in all of them.

for a middle

Explain that the synthesized copy constructor copies field values, that a List field's value is a reference, and why init stops reassignment but not Add.

for a senior

Diagnose shared mutable members in review and pick a fix that holds for every call site, such as an immutable collection type or a cloning copy constructor.

for a principal

Decide whether records in a codebase may hold mutable collections at all, since every with on them silently shares state across copies.

## The symptom A multi-tenant service keeps one baseline settings record and derives each tenant's settings from it with `with`: ```csharp var baseline = new TenantSettings("default", 30, new List<string> { "beta" }); var alpha = baseline with { TenantId = "alpha" }; var bravo = baseline with { TenantId = "bravo", TimeoutSeconds = 60 }; alpha.Tags.Add("priority-support"); Console.WriteLine(string.Join(",", bravo.Tags)); // beta,priority-support record TenantSettings(string TenantId, int TimeoutSeconds, List<string> Tags); ``` Bravo never asked for priority support, yet its tags now include it — and so do the baseline's and every other tenant's. ## Why: what the copy constructor copies For a record class, `with` calls a compiler-synthesized **copy constructor**, which copies the value of every instance field into the new object. Positional parameters become auto-properties backed by fields, so the copy receives: | Field | Type kind | What the copy holds | |---|---|---| | `TenantId` backing field | reference to an immutable `string` | the same string reference — harmless | | `TimeoutSeconds` backing field | value type `int` | its own `30` | | `Tags` backing field | reference to a mutable `List<string>` | **the same list reference** | The copy is **shallow**: one level deep. Three records now exist, but only one `List<string>`. `ReferenceEquals(alpha.Tags, baseline.Tags)` is `true`. Sharing a `string` is safe because a string cannot change; sharing a `List<string>` is not, because any holder can call `Add`, `Remove` or `Clear`. ## Why `init` does not protect you The positional property is `public List<string> Tags { get; init; }`. The `init` accessor means **the property** cannot be assigned after the object is initialized, so `alpha.Tags = new List<string>()` fails to compile. It says nothing about the object the property refers to. Microsoft's documentation describes this as **shallow immutability**: after initialization you cannot change a value-type property or the reference a reference-type property holds, but the data that reference points to can still change. ## Fixes, from local to structural 1. **Give the copy its own list in the expression.** `baseline with { TenantId = "alpha", Tags = [.. baseline.Tags] }` — the collection expression with a spread (C# 12) builds a new `List<string>` from the old items. Every call site has to remember it, so this suits a single hot spot, not a rule. 2. **Make the member immutable.** Declare `Tags` as an immutable collection type; then sharing between copies is safe because no copy can mutate it, and "adding a tag" becomes `with { Tags = Tags.Add("trial") }`, which builds a new collection. The choice among immutable and frozen collection types is covered with the collections material. 3. **Write your own copy constructor** that clones the list. Then every `with` on that record gets an independent list without call sites remembering anything; the rules for declaring one are their own subject. ## What does not fix it - Exposing a read-only interface such as `IReadOnlyList<string>` stops callers that hold the record from calling `Add` through the property, but the records still share one list, so whoever created it can still change it under all of them. - Marking the record `sealed` changes inheritance, not copying. - Switching to a `record struct` changes how the record itself is copied, but the `List<string>` field is still a reference, so the copies still share it. - `with` has no "deep" mode; any deep copy is code you write. ## How to spot it in review - Any record property typed as `List<T>`, `T[]`, `Dictionary<TKey, TValue>` or a mutable class is a candidate. - A `with` on such a record that does not list that property shares it with its source. - Tests that only compare a copy against its own expected values miss it; assert that mutating the copy's collection leaves the original's unchanged.

  • In C#, if TenantSettings were a record struct, would the with copies stop sharing the Tags list?
    No. A record struct is copied by value, but copying a struct copies its fields, and the `Tags` field still holds a reference to one `List<string>`. The struct copies would be independent for `TenantId` and `TimeoutSeconds` and still share the list. Only giving each copy a new list, or using an immutable collection, removes the sharing.
  • In C#, does the shared list also matter when nobody calls Add after the copies are made?
    Only if someone mutates it later; sharing an object no code changes is harmless. The risk is that the type invites mutation: `Tags` is a `List<string>`, so any future code holding any of the copies can call `Add` or `Clear`. Encode the intent in the type with an immutable collection rather than relying on everyone remembering.
  • In C#, why is sharing the TenantId string between copies not a problem?
    Because `string` is immutable: no operation changes a string object, every "change" returns a new one. Two records referring to the same string can never observe each other's edits, so a shallow copy of a string reference behaves like a deep copy.

Photocopying a form whose last line says "supporting papers: blue folder on shelf 3". Each copy is a separate sheet you can edit, but every copy points at the same folder, and a page added to that folder through one copy is there for all of them.

  • A with expression deep-copies lists and other reference members.
  • init on the Tags property stops anyone from adding items to the list.
  • Switching the record to a record struct makes the copies' lists independent.
  • Sealing the record changes how with copies its members.
  • The baseline's tags cannot change, because with never touches the original record.