skip to content

In C#, why does calling a mutating method on each struct element inside a foreach loop over an array leave the array unchanged?

level: middleimportance: should knowfreq 58%

answer

  1. the loop variable is not the element
  2. a copy per iteration
  3. CS1654 only for field writes
  4. an array element is a variable
  5. index with a for loop

basics

~20 s

The foreach iteration variable holds a copy of each struct element, so a mutating method changes only that copy. Assigning one of its fields fails with CS1654; to change the elements, index the array in a for loop.

solid answer

~40 s

`foreach (var p in particles)` declares a read-only iteration variable and copies each element into it. For a struct, that copy is a separate value, so `p.Fall()` changes the copy, which a `Console.WriteLine(p.Y)` inside the loop will show, while the array element keeps its old value. The compiler blocks only the obvious forms: `p.Y = 0f;` fails with CS1654, "Cannot modify members of 'p' because it is a 'foreach iteration variable'", and `p = new Particle();` fails with CS1656. A method call that writes to `this` compiles with no warning. To mutate in place, index the storage: `particles[i].Fall()` in a `for` loop works because an array element is a variable. The sturdier fix is an immutable struct whose methods return a new value that the loop writes back.

code

csharp · 21 lines
csharp
var particles = new Particle[] { new(), new() };

foreach (var p in particles)
{
    p.Fall();                 // compiles: p is a copy of the element
    p.Fall();
    Console.WriteLine($"copy inside loop: {p.Y}");      // -2
}
Console.WriteLine($"after foreach: {particles[0].Y}");  // 0

for (int i = 0; i < particles.Length; i++)
{
    particles[i].Fall();      // an array element is a variable: changed in place
}
Console.WriteLine($"after for: {particles[0].Y}");      // -1

struct Particle
{
    public float Y;
    public void Fall() => Y -= 1f;
}

go deeper

for a junior

Remember that a foreach variable holds a copy of a struct element and that a for loop with an index changes the element itself.

for a middle

Explain why field assignment gives CS1654 while a mutating method call compiles, and show the copy changing inside the loop while the array does not.

for a senior

Treat a lost foreach update as a symptom of a mutable struct, and fix the type by making it immutable rather than patching each loop.

for a principal

Weigh whether a team should allow mutable structs at all, given that every copy site loses writes silently and only readonly structs turn that into a compile error.

## What the iteration variable actually is A C# `foreach` statement declares an **iteration variable** and, on each pass, assigns it the current element. For an array, the compiler lowers the loop to an index loop that reads `array[i]` into that variable; for a `List<T>`, it reads the enumerator's `Current` property. Either way, for a **struct** element the variable receives a **copy** of the value, because assigning a value type copies it. The iteration variable is also **read-only** in the language's eyes: you cannot assign to it or to its fields. That rule exists to stop code that looks as if it edits the collection. It does not stop a method call, and that gap is where the bug lives. ## Three writes, three compiler reactions | Code inside `foreach (var p in particles)` | What the compiler does | What happens to the array | |---|---|---| | `p.Y = 0f;` | error **CS1654**: "Cannot modify members of 'p' because it is a 'foreach iteration variable'" | nothing; it does not build | | `p = new Particle();` | error **CS1656**: "Cannot assign to 'p' because it is a 'foreach iteration variable'" | nothing; it does not build | | `p.Fall();` where `Fall` assigns `Y` | compiles with no warning | unchanged: the copy in `p` changed | The third row is the surprise. A struct method that is not marked `readonly` may write to its own fields through `this`, and calling it on the iteration variable runs it against the copy. Running the program below on .NET 10 shows the copy reaching -2 inside the loop while the element stays at 0. ```csharp var particles = new Particle[] { new(), new() }; foreach (var p in particles) { p.Fall(); p.Fall(); Console.WriteLine(p.Y); // -2: the copy changed } Console.WriteLine(particles[0].Y); // 0: the element did not struct Particle { public float Y; public void Fall() => Y -= 1f; } ``` The same happens with a `List<T>` of structs, since `Current` hands out a copy too. The neighbouring trap, `list[i].Y = 0f` being rejected while `array[i].Y = 0f` is accepted, is the subject of the lesson on copying vs sharing. ## How to repair it 1. **Index the array.** `for (int i = 0; i < particles.Length; i++) particles[i].Fall();` works because an **array element is a variable**: the call runs against the storage inside the array, not a copy. 2. **Make the struct immutable and write the result back.** Give `Particle` a method that returns a new value, then assign it: `particles[i] = particles[i].Fallen();`, where `Fallen` is your own method returning a moved particle. Nothing is mutated through a copy, so nothing can be lost. 3. **Make it a class** if each particle really has identity and state that many parts of the program must see change. The array then holds references, and `p.Fall()` in a `foreach` changes the shared object. ## Why this is a design smell, not just a loop bug The loop is only where the problem shows first. A struct with a mutating method loses writes in every place C# hands out a copy: - the `foreach` iteration variable over an array or a list; - a value returned by a property getter or a method; - a struct stored in a `readonly` field or passed as an `in` parameter, where the compiler makes a hidden copy before each call to a non-`readonly` member; - a boxed copy held as `object` or an interface. That is why the design guidelines say a struct should be **immutable**, and why `readonly struct` exists: declare the struct `readonly` and `Fall` can no longer assign `Y` at all, so the struct stops compiling until `Fall` returns a new value, and the lost update becomes a compile error instead of a silent no-op. The game-loop vector in this scenario is a small value, so keeping it a struct is right; making it immutable is what removes the trap. ## What to say in an interview - The iteration variable is a **copy** of a struct element, not an alias for it. - The compiler rejects field assignment (CS1654) and reassignment (CS1656) but allows method calls, which run on the copy. - Writing through `array[i]` in a `for` loop, or writing a new value back, changes the element. - An immutable struct turns the silent bug into a compile error.

  • Would declaring the loop as `foreach (Particle p in particles)` instead of `var` change the result?
    No. `var` only infers the type of the iteration variable; with either spelling the variable has type `Particle` and receives a copy of each element. The copy still absorbs the `Fall()` call, and the array still keeps its old values. Only indexing the storage, or writing a new value back, changes an element.
  • What happens if you declare `Particle` as a `readonly struct`?
    The field `Y` must then be `readonly`, so `Fall()` can no longer assign it and the struct stops compiling until `Fall` returns a new value instead. The loop must then assign the returned value back into `particles[i]`, which writes to the array. The silent lost update becomes impossible.
  • Does the same loop over an array of a class type change the objects?
    Yes. For a class, the iteration variable holds a copy of a reference, and both the copy and the array slot point at the same object. Calling `p.Fall()` changes that shared object, so the change is visible through the array afterwards.

  • The foreach variable is a reference to the array element, so methods change the array.
  • If the code compiles, the mutation inside foreach must have taken effect.
  • Using an explicit type instead of var makes foreach mutate the element.
  • CS1654 means every mutating method call in foreach is blocked.
  • A for loop over an array copies elements just like foreach does.