C# – Collection was modified; enumeration operation may not execute – why

cenumerationnet

I'm enumerating over a collection that implements IList, and during the enumeration I am modifying the collection. I get the error, "Collection was modified; enumeration operation may not execute."

I want to know why this error occurs when modifying a item in the collection during iteration. I've already converted my foreach loop to a for loop, but I want to know the 'details' on why this error occurs.

Best Answer

From the IEnumerable documentation:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

I believe the reasoning for this decision is that it cannot be guaranteed that all types of collections can sustain modification and still preserve an enumerator state. Consider a linked list -- if you remove a node and an enumerator is currently on that node, the node reference may be its only state. And once that node is removed, the "next node" reference will be set to null, effectively invalidating the enumerator state and preventing further enumeration.

Since some collection implementations would have serious trouble with this kind of situation, it was decided to make this part of the IEnumerable interface contract. Allowing modification in some situations and not others would be horribly confusing. In addition, this would mean that existing code that might rely on modifying a collection while enumerating it would have serious problems when the collection implementation is changed. So making the behavior consistent across all enumerables is preferable.

Related Topic