Collection was modified 🟪 .NET

InvalidOperationException: Collection was modified; enumeration operation may not execute

A list/dictionary was changed while a foreach loop was iterating it.

Seen on: .NET

Meaning

Removing items inside foreach, or another thread modifying the collection during enumeration, invalidates the enumerator.

Common causes

  • Add/Remove inside foreach over the same collection
  • Concurrent modification from another thread/event
  • LINQ query re-enumerating a changing source

⚡ Quick fix

  1. Iterate over a copy (ToList())
  2. Use RemoveAll / a reverse for loop
  3. Use concurrent collections or locks for multi-threaded access

Detailed fix by platform

C#

  1. csharp
    items.RemoveAll(i => i.Expired);
    // or
    foreach (var i in items.ToList()) if (i.Expired) items.Remove(i);

How to diagnose

  1. Loop — Modifying the same collection?
  2. Threads — Concurrent writers?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.