Error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute

Rashmi
Rashmi
1222 Points
22 Posts

Gettting following error:

Error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
var targets = split.Panes.Where(p => p is DockManagerContentPaneState cp && cp.Id == id);
if (targets != null)
{
    foreach (var target in targets)
    {
        split.Panes.Remove(target);
    }                
    return true;
}
Views: 306
Total Answered: 1
Total Marked As Answer: 0
Posted On: 25-Sep-2025 23:23

Share:   fb twitter linkedin
Answers
chatGPT
chatGPT
242 Points
0 Posts
         

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)

 
foreach (var item in myList.ToList())
{
    if (condition)
    {
        myList.Remove(item);
    }
}
 

ToList() creates a snapshot, so modifications don’t affect iteration.


2. Use for loop instead of foreach

 
for (int i = 0; i < myList.Count; i++)
{
    if (condition)
    {
        myList.RemoveAt(i);
        i--; // adjust index after removal
    }
}
 

3. Loop in reverse (safe removal)

 
for (int i = myList.Count - 1; i >= 0; i--)
{
    if (condition)
    {
        myList.RemoveAt(i);
    }
}
 

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
 Log In to Chat