Simple question, I believe –> It is my understanding that an imaginary IEnumerator object is being used when I use a foreach loop over an IEnumerable object. My question is as follows:
How can I “catch” illegal behavior in foreach loops dealing with my objects? I specifically want to see if my original object from which the IEnumerable was created has been modified. If the original has been modified, I want to throw an exception.
My current approach has been to use a version number. This works great if I create an explicit iterator and use a MoveNext() or somesuch, but foreach loops seem to trick my version-based approach.
The IEnumerable interface is what actualy returns the IEnumerator it is the whole reason this interface exists.
When the foreach block is call the IEnumerable.GetEnumerator() method is called to get the enumerator.
If you want to track each item then because they are object types they will be referenced so you will have the update to date version. Within the item you could implement the versioning that you mentioned like so.
Elsewhere you could use something like this in your loop.
UPDATED
Alternatively if you just want to find out what items have changed you could do something like this.
As per dlev’s suggestion if you just want to know if any changed just use.