Search code examples
c#collectionsiteration

How to detect if the collection was modified during iteration


When iterating over a dictionary or a list or some other collection, can I somehow check if the collection was modified?

foreach (var pair in dictionary) {
   DoStuff(pair);
   if (DictionaryWasModified())
      break;
}

If DoStuff add to/removes from the dictionary, an exception will be raised on next iteration step. I want to avoid the exception.


Solution

  • The dictionary, and it's iterator, keep the information about whether the collection has changed since the last iteration private, so you can't access it. If you want to be able to iterate over a collection safely while it's being mutated, or be able to know when if it has changed since you started iteration, you'd need to make your own collection (presumably wrapping an existing collection) in which you keep track yourself whether or not it has changed, and expose that information publicly.