Collection Was Modified; Enumeraton Operation May Not Execute
Some Background
This was a very interesting bug for me to track down. Initially it did not bubble up as the error that is in this title. Initially it revealed itself as an out of bounds error when I tried to set IsOpen to true for a ContextMenu in a Silverlight project. After lots of debugging I finally landed on this culprit.
The Task
The task I was trying to accomplish was pretty straight forward. Given a List<T> remove any duplicate entries based on a given object. Again, a straight forward task, or so I thought.
foreach(MyClass item in myListOfMyClass) { if(item.SomeValue == objectOfMyClass.SomeValue) { myListOfMyClass.Remove(item); } }
The Fix
The fix is very simple. We just need to use ToList(). This gives us a list to iterate over while we modify our real list.
foreach(MyClass item in myListOfMyClass.ToList()) { if(item.SomeValue == objectOfMyClass.SomeValue) { myListOfMyClass.Remove(item); } }
Why Did This Happen
I may have to do an update for this answer as I am not 100% sure I am correct on the why. I realize that List is IEnumerable and believe it is related to the why it happened. The IEnumerable allows you to iterate over a collection but does not like for this collection to change while it is in the process of iterating over it.
Posted on July 23, 2014, in .NET, C#, Debugging and tagged Debugging, Generics. Bookmark the permalink. 1 Comment.
Reblogged this on Dinesh Ram Kali..