user168237
user168237

Reputation:

How can foreach know the iterated collection was modified?

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?

Upvotes: 10

Views: 311

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500825

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).

Upvotes: 14

Related Questions