Collection was modified; enumeration operation may not execute
April 6, 2011 5 Comments
The error occurs when you are performing a for each loop over a generic list or a collection and there is a line of code inside the loop that is trying to modify the contents of the list. Take a look at the code below :
Dim myList As New List(Of Integer) myList.Add(1) myList.Add(2) myList.Add(3) myList.Add(4) myList.Add(5) For Each i As Integer In myList myList.Remove(i) Next
the above code will throw an InvalidOperationException because we are removing items from the list while we are still iterating over its items using the for each loop.
a simple fix to the above code would be replacing the for each loop with the standard index loop as follows :
For i As Integer = 0 To myList.Count - 1 myList.Remove(i) Next