This error:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute
happens when you modify a collection while iterating over it (especially with foreach).
Why it happens
foreach uses an internal enumerator, and if the collection changes (add/remove/update structure) during iteration, the enumerator becomes invalid — so .NET throws this exception.
Common fixes
1. Iterate over a copy (most common fix)
ToList() creates a snapshot, so modifications don’t affect iteration.
2. Use for loop instead of foreach
3. Loop in reverse (safe removal)
4. If multithreading is involved
Make sure no other thread modifies the collection while you're iterating. Use locking or thread-safe collections.
⚠️ Key takeaway
- ❌ Don’t modify collection inside
foreach
- ✅ Use
ToList(), for, or reverse iteration
Posted On:
01-May-2026 00:38