Question

There is an example how enumerator migh be implemented: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx and this is a valid approach. However real List or Array invalidate their iterators when they are modified.

And my question is -- how is it done?

The best I can think of is still keeping the reference to the collection, and also some stamp (int id). Every time the collection is resized, the stamp is incremented. And on every moveNext at enumerator side, the stamp is checked -- when there is a match, enumeration continues, if not -- exception is thrown.

But this is just my wild guess, I didn't find anything solid.

Was it helpful?

Solution

how is it done?

Trivial. Keep a version counter. Compare version counter when the enumerator was created to the one currently in the enumerated object on every yield. Finished. Obviously: change version on every change.

Now, "i didn't find anything solid" - did it ever occur to you to - ah - read the source code? It is all public, you know...

http://referencesource.microsoft.com/

you look for mscorlib.

FOr example, ArrayList: http://referencesource.microsoft.com/#mscorlib/system/collections/arraylist.cs

It does not get more solid than that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top