skip to content

Why does C# reject `shelf[i].X = 5` with CS1612 when `shelf` is a `List<Point>` of structs, yet accept it on a `Point[]` array?

level: middleimportance: must knowfreq 70%

answer

  1. indexer is a method call
  2. getter returns T by value
  3. array element is a variable
  4. copy out, edit, write back

basics

~20 s

The List<T> indexer getter returns a copy of the struct, and assigning a field of that temporary copy could never reach the list, so the compiler reports CS1612. An array element is a variable, so the assignment edits it in place.

solid answer

~50 s

`List<T>` exposes `public T this[int index] { get; set; }`, so `shelf[i]` is a call to a getter that returns the `Point` by value. Setting `.X` on that temporary would be thrown away, and the compiler refuses it: CS1612, "Cannot modify the return value of 'List<Point>.this[int]' because it is not a variable". An array access like `points[i]` is not a call; it denotes the element's storage, so `points[i].X = 5` changes the stored element. The same CS1612 appears for a struct-typed property, `slot.Position.X = 5`, and for a `Dictionary<TKey,TValue>` indexer. The fix is to copy out, modify and write back (`var p = shelf[i]; p.X = 5; shelf[i] = p;`), to use an array, or to replace the element with a new value. A `List<Product>` of classes has no such error, because the copy is a reference to the shared object.

code

csharp · 12 lines
csharp
var list = new List<Point> { new Point(1, 2) };
list[0].X = 5;              // List<T> indexer returns a copy

var array = new Point[] { new Point(1, 2) };
array[0].X = 5;             // array element is a variable: allowed

struct Point
{
    public int X;
    public int Y;
    public Point(int x, int y) { X = x; Y = y; }
}

go deeper

for a junior

Remember that a List of structs hands back copies, so editing an element means reading it, changing it and assigning it back.

for a middle

Explain that the indexer is a getter returning T by value while array access names the stored element, and connect the same CS1612 to struct-typed properties.

for a senior

Choose the fix that fits the type: write-back for occasional edits, immutable values replaced whole for shared models, arrays or a span when in-place updates are hot.

for a principal

Treat repeated CS1612 workarounds as a design signal that the struct is mutable state that probably wants to be immutable or a class.

## The error and the scenario An inventory screen keeps shelf positions in a `List<Point>`, where `Point` is a **mutable struct** with public `X` and `Y` fields. Someone writes `shelf[i].X = 5;` to move an item, and the build fails: ```plaintext error CS1612: Cannot modify the return value of 'List<Point>.this[int]' because it is not a variable ``` The same line compiles if `shelf` is declared as `Point[]`. The difference is not about lists being read-only; it is about what the expression `shelf[i]` *is*. ## An indexer is a method that returns a value `List<T>` declares its indexer as `public T this[int index] { get; set; }`. Reading `shelf[i]` calls the `get` accessor, and that accessor **returns `T` by value**. For a struct, the caller receives a **temporary copy** of the stored `Point`: - the copy lives in a hidden temporary, not in the list's backing array; - assigning `.X` on it would change only the temporary; - the temporary is discarded at the end of the statement. That assignment could never have a visible effect, so C# rejects it at compile time. In the compiler's terms, the getter's result is a **value, not a variable**, and a field of a struct can be assigned only through a variable. ## An array element is a variable Array element access is built into the language. `points[i]` denotes the element's own storage inside the array, so `points[i].X = 5` writes into the array directly. No getter runs and no copy is made. | Expression | What it is | `.X = 5` | |---|---|---| | `points[i]` on `Point[]` | the stored element (a variable) | compiles, edits the array | | `shelf[i]` on `List<Point>` | a getter's return value | CS1612 | | `slot.Position` (struct auto-property) | a getter's return value | CS1612 | | `dict[key]` on `Dictionary<string, Point>` | a getter's return value | CS1612 | | `slot.Anchor` (public struct field of a class) | a variable | compiles, edits the field | | `products[i]` on `List<Product>` (class) | a copied reference | compiles, edits the shared object | The last row matters: for a **class** element, the indexer still returns a copy, but the copy is a **reference** to the one `Product` object, so setting `Price` through it changes that object. ## Fixes, in the order most code reaches for them 1. **Copy out, modify, write back.** `var p = shelf[i]; p.X = 5; shelf[i] = p;` The final assignment calls the indexer's `set` accessor and stores the modified copy. Forgetting that last line is the classic silent bug: the code compiles and the list never changes. 2. **Replace the element with a new value.** `shelf[i] = new Point(5, shelf[i].Y);` This works well when `Point` is designed as an immutable value, which the lesson on value-type trade-offs recommends. 3. **Store an array instead of a list** when the collection has a fixed size and in-place edits matter. 4. **Take a span over the list's storage.** `CollectionsMarshal.AsSpan(shelf)[i].X = 5;` works because a `Span<T>` indexer returns a `ref T`; its documentation says items should not be added to or removed from the list while the span is in use. Spans are covered with the low-allocation material. Making `X` a property instead of a field does **not** help: `shelf[i].X = 5` with an auto-property `X` is still CS1612, because the receiver is still a temporary. ## Why the compiler protects you here The rule exists to turn a silent no-op into a build error. Without it, `shelf[i].X = 5` would run, change a discarded copy and leave the shelf where it was. The protection covers **assignments** to a field or property of the temporary. It does not cover every way of mutating a temporary, which is why a mutating *method* called on `shelf[i]` is a separate, quieter trap. ## What interviewers listen for - That the candidate names the getter returning a **copy**, rather than claiming lists of structs are read-only. - That they know the array case compiles and why. - That the copy-out fix includes the **write-back** line. - That they connect the same error to a struct-typed property, the most common place it shows up in real code.

  • Why does `products[i].Price = 25m` compile on a `List<Product>` when `Product` is a class?
    The indexer still returns a copy, but for a class the copy is a reference to the one `Product` object the list holds. Setting `Price` through that reference changes the shared object, so the assignment has a visible effect and the compiler allows it.
  • Does changing `Point.X` from a public field to an auto-property make `shelf[i].X = 5` compile?
    No. The receiver `shelf[i]` is still a temporary copy returned by the indexer, so calling the `X` setter on it is rejected with the same CS1612. Only the kind of receiver matters, not whether `X` is a field or a property.
  • Which other common C# constructs raise CS1612 for a mutable struct?
    Any member access whose receiver is a returned value: a struct-typed property such as `slot.Position.X = 5`, a `Dictionary<string, Point>` indexer such as `dict["a"].X = 5`, and a method that returns a struct. A public struct field of a class or an array element does not, because those are variables.

  • CS1612 means struct fields are read-only once they are in a collection.
  • List<T> stores structs boxed on the heap, so they cannot be edited.
  • Arrays and List<T> indexers both return copies of struct elements.
  • Turning the struct's field into a property fixes CS1612.
  • Copying the element to a local and editing it updates the list.