Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "Collection was modified " error even though I'm modifying a different collection

Ok, I know that I'm not allowed to modify the collection I'm currently traversing but look at the code below and you'll witness that I'm not even touching the collection the enumeration is performed on:

    MenuItemCollection tempItems = new MenuItemCollection();
    foreach (MenuItem item in mainMenu.Items)
    {
        if (item.Value != "pen")
            tempItems.Add(item);
    }

As you can see, the collection to which I add an item is different from the one I'm iterating through. But I still get the error:

"Collection was modified; enumeration operation may not execute".

However if I make a slight change to the code and replace MenuItemCollection with List, it works:

    List<MenuItem> tempItems = new List<MenuItem>();
    foreach (MenuItem item in mainMenu.Items)
    {
        if (item.Value != "pen")
            tempItems.Add(item);
    }

Can somebody explain me why?

like image 967
Mikayil Abdullayev Avatar asked Dec 14 '25 17:12

Mikayil Abdullayev


1 Answers

When you are adding MenuItem to another MenuItemCollection it is removed from it's owner (which is mainMenu). Thus original collection is modified:

public void Add(MenuItem child)
{
    if ((child.Owner != null) && (child.Parent == null))
         child.Owner.Items.Remove(child);

    if (child.Parent != null)    
        child.Parent.ChildItems.Remove(child);

    if (this._owner != null)
    {
        child.SetParent(this._owner);
        child.SetOwner(this._owner.Owner);
    }
    // etc
}

BTW this is true both for ASP.NET and WinForms. For WinForms code will be slightly different.

like image 178
Sergey Berezovskiy Avatar answered Dec 17 '25 06:12

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!