I have a question that I am surprised hasn’t already been asked in exactly this format.
If I have an IEnumerable that is generated based on iterating through a source of data, (and using a yield return statement), how can I detect when there has been a modification to the source after an access via an Enumerator that was generated via a GetEnumerator call?
Here is the strange part: I’m not multi-threading. I think my question has a flaw in it somewhere, because this should be simple. . . I just want to know when the source has changed and the iterator is out of date.
Thank you so much.
You would need to handle creating the enumerator yourself in order to track this information, or, at a minimum use
yield return;with your own type of modification tracking in place.Most of the framework collection classes, for example, keep a “version” number. When they make an enumerator, they keep a snapshot of that version number, and check it during
MoveNext(). You could make the same check before callingyield return XXX;