Home
C#
InvalidOperationException: Collection Was Modified
This page was last reviewed on Nov 16, 2023.
Dot Net Perls
InvalidOperationException. This exception has occurred. It reports a "collection was modified" error in the program. We are trying to remove elements from a C# List.
With some code changes, we can fix the problem. It is important to know that the foreach-loop has some restrictions. We cannot change the underlying collection in while foreach is running.
foreach
First example. We see a program that can cause this exception. The example demonstrates a List and a foreach-loop that tries to remove an item, but raises an exception.
Exception
List
Start We create a List of 3 integers with a list initializer. We then enter a foreach-loop over the list.
List Initialize
Next The loop iterates over each item in the list. We call the Remove method, and it tries to modify the collection during the loop.
using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<int>() { 10, 20, 30 }; // Try to remove an element in a foreach list. foreach (int value in list) { Console.WriteLine("ELEMENT: {0}", value); list.Remove(value); } } }
ELEMENT: 10 Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.ThrowHelper. ThrowInvalidOperationException(ExceptionResource resource) at System.Collections. Generic.List`1.Enumerator.MoveNextRare() at System.Collections. Generic.List`1.Enumerator.MoveNext() at Program.Main()...
Example 2. This example removes list elements, without raising an exception. We can call Remove() on the List in a for-loop (with indexes).
for
Info RemoveAt is another method we could call. It will accept the index of the item we want to remove—it might be faster.
List Remove
Tip This might be the best way to remove items from a List without causing an exception. RemoveAll() receives a lambda.
List RemoveAll
Here This program removes all elements in the list where the value is equal to 20.
using System; using System.Collections.Generic; class Program { static void Main() { var list = new List<int>() { 10, 20, 30 }; // Remove elements from the list in a for-loop. for (int i = 0; i < list.Count; i++) { int value = list[i]; // Remove if value is 20. if (value == 20) { list.Remove(value); } } // Write list after element removed. foreach (int value in list) { Console.WriteLine("ELEMENT: {0}", value); } } }
ELEMENT: 10 ELEMENT: 30
Summary. An InvalidOperationException is not useful. But the "collection was modified" error message can be informative. RemoveAll can be used to safely remove items from a List.
And with a for-loop, we can remove elements by their indexes. RemoveAt can be used. Alternatively, another new list of elements can be created from the elements we wish to keep.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 16, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.