In C#, why does rules.Add("gbp-rounding") leave an ImmutableList<string> unchanged, and how do you fix the code?
answer
- look at the return type
- the original instance never changes
- assign the result back
basics
~10 sImmutableList<T>.Add never changes the list it is called on; it returns a new ImmutableList<T> containing the item. Code that ignores the return value throws the new list away. Assign it: rules = rules.Add("gbp-rounding").
solid answer
~40 sEvery mutating-looking method on the `System.Collections.Immutable` types (`Add`, `AddRange`, `Remove`, `Insert`, `SetItem`) returns a **new** collection and leaves the receiver untouched. `rules.Add("gbp-rounding");` compiles, builds a new list, and drops it, so `rules.Count` is still 2. The fix is to keep the result: `rules = rules.Add("gbp-rounding");`, or assign it to a new variable when the old version is still needed. The trap is the same on `ImmutableArray<T>`, a struct, and nothing warns: on the .NET 10 SDK even `AnalysisMode=All` reports CA1806 for a discarded `string.ToUpperInvariant()` result but stays silent on a discarded `ImmutableList<T>.Add`. It is the same habit as `string.Replace`, so reviewers should watch for any statement that calls one of these methods without using its result.
code
csharp · 16 linesusing System.Collections.Immutable;
ImmutableList<string> rules = ImmutableList.Create("eur-rounding", "usd-rounding");
rules.Add("gbp-rounding"); // compiles, returns a new list, result dropped
Console.WriteLine(rules.Count); // 2
ImmutableList<string> updated = rules.Add("gbp-rounding");
Console.WriteLine($"{rules.Count} {updated.Count}"); // 2 3
rules = rules.Add("gbp-rounding"); // the fix: keep the new version
Console.WriteLine(rules.Count); // 3
ImmutableArray<string> codes = ["EUR", "USD"];
codes.Add("GBP"); // same trap on the struct type
Console.WriteLine(codes.Length); // 2go deeper
Recall that methods on immutable collections return a new collection, so the result must be assigned to be kept.
Explain that the receiver never changes, show the reassignment fix, and mention builders for many changes in a row.
Point out that no analyzer flags it, so it needs review discipline, and that a shared field also needs a compare-and-swap to publish safely.
Weigh the readability of List-like method names against how easily they invite this bug when a team adopts immutable types.
## The bug A developer switches a rules list from `List<string>` to `ImmutableList<string>` so that request threads can read it safely, and keeps the old calling code: ```csharp rules.Add("gbp-rounding"); Console.WriteLine(rules.Count); // still 2 ``` The code compiles and runs without an exception, but the new rule never appears. Nothing is wrong with the collection; the code is using it as if it were mutable. ## Why it happens An **immutable collection** is one whose instance never changes after it has been created. The types in `System.Collections.Immutable` keep that promise by turning every operation that would change the contents into a method that **returns a new collection**: | Call | Returns | Effect on the receiver | |---|---|---| | `ImmutableList<T>.Add(item)` | a new `ImmutableList<T>` | none | | `ImmutableList<T>.Remove(item)` | a new `ImmutableList<T>` | none | | `ImmutableArray<T>.Add(item)` | a new `ImmutableArray<T>` | none | | `ImmutableDictionary<TKey,TValue>.SetItem(key, value)` | a new dictionary | none | | `List<T>.Add(item)` | `void` | the list grows | So `rules.Add("gbp-rounding")` does all the work of building a list with three elements and then the statement ends. The new list is unreachable, and the garbage collector reclaims it. `rules` still refers to the original two-element list, which by design can never change. The method names were kept close to `List<T>` on purpose, so code reads naturally. The price is that a statement that discards the result looks exactly like correct mutable code. ## The fix Keep the value the method returns: 1. **Reassign the variable** when only the latest version matters: `rules = rules.Add("gbp-rounding");`. 2. **Use a new variable** when both versions are needed: `var updated = rules.Add("gbp-rounding");`. The old `rules` is still a valid snapshot, which is often the reason for choosing an immutable type in the first place. 3. **Use a builder** when many changes happen in a row: `var builder = rules.ToBuilder();`, call `builder.Add` as often as needed (it really does mutate the builder), then `rules = builder.ToImmutable();`. 4. **Publish with a compare-and-swap** when the variable is a shared field that other threads also replace: `ImmutableInterlocked.Update(ref _rules, r => r.Add("gbp-rounding"));`. Plain reassignment from two threads at once can lose one of the changes. ## Why nothing warns The compiler accepts an expression statement whose result is ignored; that is how C# works for any method that returns a value. Code analysis has a rule for the general idea, **CA1806 (Do not ignore method results)**, which covers new strings, LINQ methods and methods marked `[Pure]`. On the .NET 10 SDK, with `AnalysisMode=All`, CA1806 fires for a discarded `string.ToUpperInvariant()` but not for a discarded `ImmutableList<T>.Add` or `ImmutableArray<T>.Add`: the immutable methods carry no `[Pure]` attribute in the source. Code review is the guard. ## Builders flip the rule The confusion gets worse in code that mixes the two worlds. On an `ImmutableList<T>.Builder` or `ImmutableArray<T>.Builder`, `builder.Add(item);` as a bare statement is **correct**: the builder is a mutable collection, and its `Add` returns `void`. On the immutable collection itself, the same-looking statement is the bug. A method that receives "something with an `Add`" therefore has to know which one it has, and naming variables `rulesBuilder` and `rules` helps reviewers tell them apart. ## The same shape across the namespace The pattern is uniform, so the habit transfers: - `ImmutableHashSet<T>.Add` and `ImmutableSortedSet<T>.Add` return new sets. - `ImmutableDictionary<TKey,TValue>.Add`, `SetItem` and `Remove` return new dictionaries. - `ImmutableStack<T>.Push` and `ImmutableQueue<T>.Enqueue` return a new stack or queue. - The interfaces follow suit: `IImmutableList<T>.Add` returns an `IImmutableList<T>`, so code written against the interface has the same trap. ## Signs to look for in review - A statement that is only `x.Add(...)`, `x.Remove(...)` or `x.SetItem(...)` where `x` is an immutable type. - An `ImmutableArray<T>` or `ImmutableList<T>` field assigned once and "updated" with no assignment anywhere. - Tests that check `Count` after an `Add` and pass only because they assert on the returned value, not on the field. ## A test that catches it A unit test catches the bug only if it asserts on the state the code under test keeps, not on a value it returns. For a class that owns `private ImmutableList<string> _rules`, call the public method that should add a rule, then read the rules back through the class's own getter and assert the count. A test that asserts on the return value of `_rules.Add(...)` inside the method proves nothing, because that value exists whether or not it was stored. The same habit protects you with `string`: `name.Trim();` on its own does nothing either, because strings are immutable in the same way.
- Does the discarded new list cost anything?Yes. `ImmutableList<T>.Add` allocates the new tree nodes along one path, and `ImmutableArray<T>.Add` allocates and copies an entire new array. That work is done and then thrown away, so the bug wastes allocations as well as losing the item.
- Where else in .NET does the same discarded-result mistake show up?Anywhere a type is immutable: `string.Replace`, `Trim` and `ToUpper` return new strings, and `DateTime.AddDays` returns a new `DateTime`. Calling them as statements does nothing. CA1806 catches the string cases, which is why the immutable collection case, which it misses, surprises people.
- ImmutableList<T>.Add throws an exception because the list is immutable
- Calling Add on an ImmutableList<T> changes it like List<T>.Add
- The compiler reports an error when Add's result is ignored
- Wrapping the call in a lock makes the item appear in the list
- Only ImmutableList<T> has this problem; ImmutableArray<T> changes in place