C# custom Iterator implementation - prevent collection modification during foreach loop?

You'd need to have a version ID within your class. Increment it on entry to Add When you create an iterator (in the GetEnumerator() call) you would remember the version number - and on each iteration, you'd check whether the version number is still what it was to start with, throwing otherwise.

You'd need to have a version ID within your class. Increment it on entry to Add. When you create an iterator (in the GetEnumerator() call) you would remember the version number - and on each iteration, you'd check whether the version number is still what it was to start with, throwing otherwise.

Thanks Jon. A really simple solution. Seems kind of obvious now.

=) – Marko G Nov 16 at 15:59.

You can add a field to your collection that you can increment every time the collection is modified. When the enumerator is created you store the value of this field in the enumerator. When the enumerator is used you verify that current value of field is the same as the value stored when the enumerator was created.

If not you throw an InvalidOperationException.

You could use a list instead of temp array in your code and that will throw InvalidOperationException by default anyway. Secondly you could get by using generic version of IEnumerable and you may not have to do the hard work of creating a custom iterator.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions