Fix "Collection was modified; enumeration operation may not execute"
Codemia Knowledge Hub ·
This exception is thrown when a collection (a list, dictionary and so on) is modified while it is being enumerated, for example by adding or removing items inside a foreach loop. The fix is to stop changing the collection you are iterating: iterate over a copy, use an index-based for loop, or use a thread-safe collection when other threads modify it. The message comes from .NET (C#), and other platforms such as Java perform similar checks during iteration.
Why the enumerator throws
Most collection classes are not safe for modification during enumeration. When you start enumerating, the collection's internal state is tracked. If the collection detects a structural change (such as an addition or removal), it invalidates the enumerator, and the next access to the enumerator throws.
This C# code triggers it:
The list numbers is modified (an item is removed) while the foreach loop is iterating it.
Fix 1: iterate over a copy
Copy the collection first, iterate over the copy, and modify the original:
Fix 2: use a for loop instead of foreach
An index-based loop lets you adjust the counter after a removal:
Fix 3: use concurrent collections across threads
In multithreaded code, thread-safe .NET collections such as ConcurrentBag, ConcurrentDictionary or BlockingCollection prevent this error.
Other options: locking and immutable collections
- Custom synchronization: where concurrent collections are not available or suitable, your own locks can make modification safe.
- Immutable collections: these cannot be modified after creation. Any "modification" creates a new collection, which avoids the problem entirely.
Which fix to choose
| Strategy | Description | Suitable Use-Case |
| Copy the Collection | Iterating over a duplicate while modifying the original | Non-concurrent environments |
| Use for Loop Instead of foreach | Manipulate loop counter to adjust size changes | Small to medium collections |
| Use Concurrent Collections | Collections designed for safe multi-threading | Multi-threaded applications |
| Implement Custom Synchronization | Programming controlled locks and synchronization | Advanced use cases requiring fine-grained control |
| Utilizing Immutable Collections | Use collections that do not allow modifications | Functional programming paradigms or where immutability is a requirement |
Related reading
- CollectionView sizeForItemAtIndexPath never called
- com.apple.WebKit.WebContent drops 113 error Could not find specified service
- com.jcraft.jsch.JSchException UnknownHostKey
- Command CompileSwift failed with a nonzero exit code in Xcode 10
- Command CompileSwiftSources failed with a nonzero exit code XCode 13
- Command failed due to signal Segmentation fault 11
- Command failed on instance. An unexpected error has occurred ErrorCode 0000000001
- command line authentication of mongo fails
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseInterview Questions practice on Codemia
Over 11,000 interview practice questions for 300+ companies, searchable by company and role.