Collection was modified; enumeration operation might not execute

“Collection was modified; enumeration operation might not execute”  this common error developer faces every time he is updating(add/delete/sort) the collection which is being enumerated.

The question is why this happens, it understandable that Deleting and Sorting might change the way index might have sorted into but Adding should work fine – if there is no sort defined.

All this is related to the way MS has implemented enumeration for its classes.

Take List<T> as an example.

In List, there is an internal variable by name “version” which is incremented on any kind of operation done on list, this includes Add, Delete, Sort. Now when enumerator object is requested from List, internally list instantiate a struct (Enumerator) which implements IEnumerator.

Initialization of struct enumerator requires list as its mandatory parameter and locally notes down current “version” of list You can think struct enumerator as Linked-list implementation using arrays.

“MoveNext()” API call, It first checks the version noted by enumerator and list matches, secondly gives the reference of next element in the array/list.

Whenever mismatch happens exception is thrown.

All above is said about MS implementation. If you create custom collection class and override GetEnumerator function you won’t receive the error.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s