Collection was modified; enumeration operation may not execute – why?

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.

Leave a Comment

tech