When enumerating a .NET collection, MSDN states that:
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.
What exactly does "irrecoverably invalidated" mean?
Take a binary tree for instance, with references both down to left and right children, and also up to parent. In such a tree, a single reference to a single node in the tree is enough to navigate through the tree as you can easily find the next node in the tree from it.
So with that tree, suppose I remove some other node (presumably, I don't remove the node I'm currently sitting in), should I still invalidate the enumerator? Note that I'm not talking about multi-threaded operation here, just a single thread running a loop, and modifying the collection inside the loop body.
Is this "law" really that, a law, that even if the enumerator could continue, it shouldn't?
Is this "law" really that, a law, that even if the enumerator could continue, it shouldn't?
Personally, I think that having your enumerator throw, even if it theoretically could continue, is a good practice.
Often, people inadvertently put code that changes a collection inside of a foreach loop. Without doing this, it might not be throwing in the specific instance the developer is currently testing, but a different runtime condition could easily make it throw.
By always throwing, you're forcing the developer to treat your code the same as the framework's collections and enumerations, which I think is a good thing, since it reduces the level of surprise when dealing with your library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With