Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

Modifying a collection while enumerating

Why foreach throws InvalidOperationException when a List or Dictionary changes during enumeration, which collections allow it and the safe patterns to use instead.

If you add or remove items from a List<T>, Dictionary<TKey,TValue>, HashSet<T>, Queue<T> or Stack<T> while a foreach loop is enumerating it, the next step of the loop throws InvalidOperationException with the message "Collection was modified; enumeration operation may not execute." The collection keeps a hidden version number, increments it on each structural change, and the enumerator compares it on every MoveNext.

The check protects you from skipped or repeated items. The fix is never to catch the exception: change the loop so it does not mutate the collection it is walking.

C#
var items = new List<int> { 1, 2, 3 };
foreach (var x in items)
{
    items.Remove(x);   // throws on the next iteration
}

Try it

C# The exception, and safe alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Dictionaries, sets and the last step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

There is no special syntax: the behavior comes from the enumerator returned by GetEnumerator() and the foreach statement. In pseudocode:

C#
// foreach (var x in list) { body }  compiles to roughly:
using var e = list.GetEnumerator();   // remembers list._version
while (e.MoveNext())                  // throws if list._version changed
{
    var x = e.Current;
    // body
}

Errors: InvalidOperationException, "Collection was modified; enumeration operation may not execute." Collections that throw: List<T> (add, insert, remove, clear, sort, reverse), HashSet<T>, Queue<T>, Stack<T>, LinkedList<T>, SortedSet<T>. Dictionary<TKey,TValue> allows Remove and Clear during enumeration (since .NET Core 3.0) but still throws when you add a key.

Usage notes

  • Replacing an element by index (list[i] = x) does not change the structure, but in List<T> it still counts as a modification and throws inside foreach; assigning an existing key of a Dictionary does not throw. A for loop with an index is the right tool if you must update items.
  • The check happens in MoveNext, not at the mutation itself, so the loop body finishes its current iteration first. A change on the very last iteration still throws, because the final MoveNext compares versions before it reports the end.
  • Prefer the bulk methods: List<T>.RemoveAll, HashSet<T>.RemoveWhere and Dictionary<TKey,TValue>.Remove after collecting keys.
  • Iterate over a snapshot (ToList(), ToArray()) when you must mutate the original; it costs O(n) memory.
  • ConcurrentDictionary<TKey,TValue> and the other concurrent collections allow changes during enumeration: the enumerator may or may not show them.
  • Immutable collections never change, so enumerating them while "modifying" is safe: you work on a new instance.
  • With multiple threads, this exception can also be thrown when another thread changes a plain collection. Lock around the whole loop or use a concurrent collection.