skip to content

In C#, why does removing items from a List<T> inside a foreach over that list throw, and which loop rewrites are safe?

level: middleimportance: must knowfreq 60%

answer

  1. the enumerator notices the list changed
  2. Collection was modified
  3. indexes shift after RemoveAt
  4. walk backwards, or remove in one pass

basics

~10 s

List<T>'s enumerator detects any change to the list and the next step of foreach throws InvalidOperationException. Remove with a backward for loop and RemoveAt, call RemoveAll with a predicate, or loop over a copy.

solid answer

~40 s

A `foreach` over a `List<T>` is driven by the list's enumerator, which records the list's internal version when the loop starts. `Remove`, `Add`, `RemoveAt` and even the indexer's setter change that version, so the next `MoveNext` throws `InvalidOperationException`: "Collection was modified; enumeration operation may not execute." Safe rewrites: a `for` loop that runs from `Count - 1` down to `0` and calls `RemoveAt(i)`; `list.RemoveAll(predicate)`, which compacts the list in a single pass; or `foreach` over a copy such as `list.ToArray()` while removing from the original. A forward `for` loop with `RemoveAt(i)` does not throw but is wrong: every removal shifts the next item into index `i`, and `i++` then skips it.

code

csharp · 30 lines
csharp
var pending = new List<string> { "", "", "AB-123", "CD-456", "" };
try
{
    foreach (string plate in pending)
    {
        if (plate.Length == 0) pending.Remove(plate);
    }
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"foreach: {ex.GetType().Name}: {ex.Message}");
}

var forward = new List<string> { "", "", "AB-123", "CD-456", "" };
for (int i = 0; i < forward.Count; i++)
{
    if (forward[i].Length == 0) forward.RemoveAt(i);   // skips the next item
}
Console.WriteLine($"forward for: {forward.Count} left, first item blank: {forward[0].Length == 0}");

var backward = new List<string> { "", "", "AB-123", "CD-456", "" };
for (int i = backward.Count - 1; i >= 0; i--)
{
    if (backward[i].Length == 0) backward.RemoveAt(i);
}
Console.WriteLine($"backward for: {backward.Count} left");

var bulk = new List<string> { "", "", "AB-123", "CD-456", "" };
int removed = bulk.RemoveAll(plate => plate.Length == 0);
Console.WriteLine($"RemoveAll: removed {removed}, {bulk.Count} left");

go deeper

for a junior

Recall that modifying a List<T> inside foreach over it throws InvalidOperationException, and that RemoveAll or a backward for loop is the safe way to drop items.

for a middle

Explain the version check that fires on the next MoveNext, why a forward for with RemoveAt skips items, and when iterating a copy is the better rewrite.

for a senior

Spot the latent version of this bug in review, such as a remove-then-break or an indexer write in a foreach, and choose the rewrite that fits the body's side effects.

for a principal

Little to decide at lead level; a review checklist item for mutating the collection a foreach is walking catches this more cheaply than a design debate.

A garage controller keeps a `List<string>` of pending licence plates, and blank plates (failed camera reads) must be dropped before the batch is sent. The first draft removes them inside the loop that finds them, and it throws. The C# behaviour behind that failure, and the three rewrites that work, are a staple of code reviews and interviews. ## Why foreach plus Remove throws - `foreach (string plate in pending)` asks the list for its **enumerator** and calls `MoveNext()` before every iteration. - `List<T>` keeps a private **version** number that its mutating members increment, among them `Add`, `Insert`, `Remove` (when it finds the item), `RemoveAt`, `RemoveAll`, `Clear`, `Sort`, `Reverse` and the **indexer's setter** (`list[i] = x`). - The enumerator copies that version when it is created. On each `MoveNext()` it compares, and if the list has changed it throws `InvalidOperationException` with the message "Collection was modified; enumeration operation may not execute." So the exception does not come from `Remove` itself; it comes from the *next* `MoveNext()`. That has two consequences worth knowing: 1. If you remove one item and immediately `break`, no further `MoveNext()` runs and nothing throws. That is legal, but fragile when the code later changes. 2. Changing the **objects** in the list (setting a property on each element) is fine, because it does not change the list. How `foreach` finds and drives the enumerator, and the general contract that enumerators may detect modification, are covered with the enumerator material; here the point is how to write the loop. ## The wrong fix: a forward for loop ```csharp for (int i = 0; i < pending.Count; i++) if (pending[i].Length == 0) pending.RemoveAt(i); ``` This never throws, because there is no enumerator. It is still wrong: after `RemoveAt(i)` every later element moves down one index, so the element that was at `i + 1` is now at `i`, and the loop's `i++` steps past it. With two blanks in a row, the second survives. On the list `"", "", "AB-123", "CD-456", ""` it leaves three items, the first of them blank. ## Three rewrites that work | approach | cost | notes | |---|---|---| | `for` from `Count - 1` down to `0` with `RemoveAt(i)` | each `RemoveAt` shifts the items after `i` | removals only move elements already visited | | `list.RemoveAll(p => p.Length == 0)` | one pass over the list | returns how many items it removed | | `foreach` over `list.ToArray()`, calling `list.Remove(p)` | a full copy, and each `Remove` searches again | easiest to read when the body does more than remove | - **Walking backwards** works because removing index `i` moves only elements with a higher index, and the loop has already visited those. - **`RemoveAll(Predicate<T>)`** is usually the best answer for a pure filter: it walks the list once, copies each kept element down into the next free slot, and fixes up the count at the end. - **Iterating a copy** decouples the enumeration from the mutation. It is the right shape when the loop body also logs, raises events or calls other services for each removed item, but it allocates the copy, and each `Remove(item)` searches the list again from the start for the first equal item. - Building a **new list** of the items to keep is another safe option, and it leaves the original untouched for callers that still hold it. ## Other collections The rule is a property of each collection's enumerator, so it is not uniform. Adding to a `Dictionary<TKey,TValue>` inside a `foreach` over it throws, but on .NET 10 calling `Remove` on the dictionary during that `foreach` completes without an exception. Arrays cannot shrink at all. `ConcurrentDictionary<TKey,TValue>` documents that its enumerator is safe to use while the dictionary is being read and written. Do not generalise from one type to another; check the type you are iterating. ## What to say in a review - A `foreach` body that calls `Add`, `Remove` or the indexer setter on the collection being iterated is a bug, even if the current data happens not to trigger it. - A forward `for` loop that calls `RemoveAt(i)` needs either `i--` after the removal or a rewrite. - Prefer `RemoveAll` for filtering, a backward `for` when the index matters, and a copy when the body has side effects.

  • In C#, does assigning list[i] = value inside a foreach over that same List<T> also throw?
    Yes. The `List<T>` indexer's setter increments the list's version just like `Add` and `Remove`, so the next `MoveNext()` throws `InvalidOperationException`. To replace elements while walking the list, use a `for` loop over the indexes, which has no enumerator to invalidate.
  • In C#, how would you fix a forward for loop that calls RemoveAt(i) and skips items?
    Either decrement `i` after each removal (`list.RemoveAt(i); i--;`) so the shifted element is examined, or run the loop from `Count - 1` down to `0`, where removals only move elements already visited. For a pure filter, `RemoveAll(predicate)` replaces the loop entirely and does the work in one pass.
  • In C#, why can removing one List<T> item inside foreach and then breaking avoid the exception?
    The exception is thrown by the enumerator's next `MoveNext()`, not by `Remove`. If the loop `break`s right after the removal, `MoveNext()` is never called again, so nothing throws. It works, but a later edit that removes the `break` reintroduces the bug, so many reviewers still ask for `Remove` outside the loop.

  • Says List<T>.Remove itself throws when called during foreach.
  • Thinks a forward for loop with RemoveAt(i) removes every matching item.
  • Believes only Add and Remove invalidate the enumerator, never the indexer setter.
  • Thinks every .NET collection throws the same way when modified during foreach.
  • Believes changing a property of an element during foreach throws too.