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.

Advertisements

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on July 23, 2014, in .NET, C#, Debugging and tagged , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: