When I modified the collection I was iterating through with foreach
, I got an exception. So I'm just curious about how foreach
(or the runtime) detect that. Is it possible to do so with a general object?
views:
86answers:
1
+13
A:
The collection itself has to detect it. In the standard library collections, this is achieved by having an internal version number which is modified by each operation, and checked by the iterator on each iteration (i.e. each time you call MoveNext
it checks that the version number is the same as it was when the iterator was created).
Jon Skeet
2010-10-04 06:33:24