In C#, `shelf[i].MoveBy(1, 0)` on a `List<Point>` of mutable structs compiles without a warning, yet the item never moves; why, and how do you fix it?
answer
- what the receiver of the call is
- temporary copy, then discarded
- CS1612 covers assignments only
- write back or stop mutating
basics
~20 sThe List<T> indexer returns a copy of the struct, and C# lets a method run on that temporary copy, so MoveBy changes the copy and the copy is discarded. Write the copy back, use an array, or make the struct immutable.
solid answer
~40 s`shelf[i]` calls the `List<T>` getter, which returns the `Point` by value. C# rejects assigning a field of that temporary (CS1612), but it allows calling a method on it, because many methods called on a struct value only read it. So `MoveBy` mutates a hidden copy that is thrown away, and nothing reports it. A struct-typed property behaves the same: `slot.Position.MoveBy(3, 0)` moves a copy, while a public struct field, `slot.Anchor.MoveBy(3, 0)`, moves the stored value. Fixes: copy out, call, write back (`var p = shelf[i]; p.MoveBy(1, 0); shelf[i] = p;`); return a new value instead of mutating (`shelf[i] = shelf[i].Moved(1, 0)`); keep the data in an array; or call through `CollectionsMarshal.AsSpan(shelf)[i]`. The durable fix is an immutable `Point`, so no mutating method exists to call on a copy.
code
csharp · 28 linesusing System.Runtime.InteropServices;
var shelf = new List<Point> { new Point(1, 2) };
shelf[0].MoveBy(3, 0); // compiles: runs on a temporary copy
Console.WriteLine($"after shelf[0].MoveBy: X = {shelf[0].X}");
var slot = new Slot();
slot.Position.MoveBy(3, 0); // property getter returns a copy
Console.WriteLine($"after slot.Position.MoveBy: X = {slot.Position.X}");
slot.Anchor.MoveBy(3, 0); // public field: the stored value itself
Console.WriteLine($"after slot.Anchor.MoveBy: X = {slot.Anchor.X}");
CollectionsMarshal.AsSpan(shelf)[0].MoveBy(3, 0); // ref to the list's own backing element
Console.WriteLine($"after span MoveBy: X = {shelf[0].X}");
struct Point
{
public int X;
public int Y;
public Point(int x, int y) { X = x; Y = y; }
public void MoveBy(int dx, int dy) { X += dx; Y += dy; }
}
class Slot
{
public Point Position { get; set; } = new Point(1, 2);
public Point Anchor = new Point(1, 2);
}go deeper
Recall that a List of structs and a struct-typed property both hand back copies, so a method called on them works on a copy.
Explain the hidden temporary the compiler creates for the call and why CS1612 rejects field assignments but not method calls.
Diagnose lost writes by checking the receiver of each mutating call, and fix them with write-back, whole-value replacement or an immutable struct.
Use these bugs to argue for immutable value types as a codebase norm, so no mutating method can ever run on a copy.
## The symptom The inventory screen stores shelf positions in a `List<Point>`, and `Point` is a **mutable struct** with a `MoveBy(int dx, int dy)` method that adds to its own `X` and `Y`. A drag handler calls `shelf[i].MoveBy(1, 0);`. The project builds with no error and no warning, the handler runs, and the item stays where it was. Nothing throws, so the bug surfaces only as "moving does nothing". ## What the compiler generates `List<T>` declares its indexer as `public T this[int index] { get; set; }`. The expression `shelf[i]` therefore calls the **get accessor**, which returns the element **by value**. To call an instance method on a struct, the compiler needs a location for `this`, so it stores the returned value in a hidden **temporary** and calls `MoveBy` on that temporary: 1. call `get_Item(i)` and copy the result into a temporary `Point`; 2. call `MoveBy` with `this` referring to the temporary; 3. discard the temporary at the end of the statement. The list's backing array is never touched. The setter, which is the only path that writes into the list, is never called. ## Why there is no CS1612 here C# does reject `shelf[i].X = 5` with CS1612, "Cannot modify the return value of 'List<Point>.this[int]' because it is not a variable". That rule covers **assigning** a field or property of a returned value. A **method call** on a returned struct value is allowed, because calls such as `ToString()`, `Equals(...)` or a distance calculation only read the value, and the compiler does not analyse whether an ordinary method body writes to `this`. The lost write is therefore legal code. ## Where the same trap appears | Receiver | What `MoveBy` mutates | Result | |---|---|---| | `shelf[i]` on `List<Point>` | a temporary copy | lost | | `slot.Position` (struct auto-property) | a temporary copy | lost | | `dict[key]` on `Dictionary<string, Point>` | a temporary copy | lost | | `slot.Anchor` (public struct field of a class) | the stored field | kept | | `points[i]` on `Point[]` | the stored element | kept | | `CollectionsMarshal.AsSpan(shelf)[i]` | the list's backing element | kept | The rule behind the table: a field or array element is a **variable**, so a method call on it runs on the stored value; a property or indexer is a **method that returns a copy**. ## Fixes and when each one fits - **Copy out, call, write back.** `var p = shelf[i]; p.MoveBy(1, 0); shelf[i] = p;` Correct and explicit, but easy to forget the last line. - **Return a new value instead of mutating.** Give `Point` a method such as `Moved(int dx, int dy)` that returns a new `Point`, and write `shelf[i] = shelf[i].Moved(1, 0);`. The assignment makes the write-back impossible to forget. - **Store an array** when the collection is fixed-size and edited in place often. - **Use a span over the list's storage** with `CollectionsMarshal.AsSpan`, whose indexer returns a `ref` to the element; its documentation says items should not be added to or removed from the list while the span is in use. Spans belong to the low-allocation material. - **Make the struct immutable.** If `Point` has no method that mutates it, the trap cannot be written at all. The mechanics of `readonly struct` and readonly members are covered with value-type trade-offs. - **Make it a class** if the screen really wants shared identity, so every holder sees one moving object. ## Diagnosing it in a real codebase When a value "refuses to change", check the **receiver** of the mutating call rather than the method body: - if the receiver is a property, an indexer or a method result and its type is a struct, the call ran on a copy; - search for mutating struct methods called through `[` indexers or property chains; - a unit test that reads the element back after the call catches it at once, because the method itself works when called on a variable. A candidate who names the temporary copy, explains why CS1612 does not fire, and proposes an immutable value type with whole-element replacement has shown both the mechanism and the design lesson.
- Why does `slot.Anchor.MoveBy(3, 0)` move the point when `slot.Position.MoveBy(3, 0)` does not?`Anchor` is a public field, so `slot.Anchor` is a variable: the call runs with `this` referring to the field inside the `Slot` object. `Position` is a property, so `slot.Position` calls the getter and the call runs on the returned copy.
- If you keep `Point` mutable, what is the safest way to update an element of a `List<Point>`?Copy it into a local, mutate the local, and assign it back with `shelf[i] = p;`, which calls the indexer's setter. Wrapping that in one helper method keeps the write-back from being forgotten. Better still, add a method that returns a new `Point` and assign its result.
- If the call compiles, the mutation must have reached the list.
- The JIT optimised away the MoveBy call in a Release build.
- Turning the public Anchor field into an auto-property makes the move stick.
- List<T> silently rejects changes to struct elements at run time.
- Calling the method twice makes the second call see the first.