Programming
Error Handling
Collection Modification
Enumeration Operation
Debugging

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:

csharp
1List<int> numbers = new List<int> {1, 2, 3, 4, 5};
2foreach (int number in numbers)
3{
4    if (number % 2 == 0)
5    {
6        numbers.Remove(number);
7    }
8}

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:

csharp
1   List<int> original = new List<int> {1, 2, 3, 4, 5};
2   List<int> copy = new List<int>(original);
3   foreach (int number in copy)
4   {
5       if (number % 2 == 0)
6       {
7           original.Remove(number);
8       }
9   }

Fix 2: use a for loop instead of foreach

An index-based loop lets you adjust the counter after a removal:

csharp
1   List<int> numbers = new List<int> {1, 2, 3, 4, 5};
2   for (int i = 0; i < numbers.Count; i++)
3   {
4       if (numbers[i] % 2 == 0)
5       {
6           numbers.RemoveAt(i);
7           i--; // Decrement i to adjust for the change in size
8       }
9   }

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

StrategyDescriptionSuitable Use-Case
Copy the CollectionIterating over a duplicate while modifying the originalNon-concurrent environments
Use for Loop Instead of foreachManipulate loop counter to adjust size changesSmall to medium collections
Use Concurrent CollectionsCollections designed for safe multi-threadingMulti-threaded applications
Implement Custom SynchronizationProgramming controlled locks and synchronizationAdvanced use cases requiring fine-grained control
Utilizing Immutable CollectionsUse collections that do not allow modificationsFunctional programming paradigms or where immutability is a requirement

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Interview Questions practice on Codemia

Over 11,000 interview practice questions for 300+ companies, searchable by company and role.

Browse interview questions