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?
When you are adding
MenuItemto anotherMenuItemCollectionit is removed from it’s owner (which ismainMenu). Thus original collection is modified:BTW this is true both for ASP.NET and WinForms. For WinForms code will be slightly different.