InvalidOperationException on modifying List<T> during foreach enumeration
0 reputation · 28 Dec 2024, 04:20 UTC
Problem Context
When a structural change is made to a List inside a foreach loop, the runtime throws an InvalidOperationException. The exception message indicates that the collection was modified during enumeration.
Goal
Identify the precise performance cost of the enumerator’s version check and evaluate whether a zero‑allocation safe iteration helper would be beneficial before refactoring code that currently relies on this exception.
Constraints & Uncertainty
The enumerator stores a version field that is compared on every MoveNext call. It is unclear how much overhead this adds relative to the loop body and whether the exception check itself dominates the hot path. Additionally, the language does not expose a built‑in snapshot or safe‑foreach construct, leaving a design decision unresolved.
Questions
- Does .NET provide a zero‑allocation safe foreach helper that automatically snapshots the collection?
- What is the measured allocation and cycle cost of the enumerator’s version check compared to a simple for loop?
- Should developers manually snapshot the collection or rely on existing libraries to avoid the InvalidOperationException?