the collection was modified. enumeration operation may not execute RRS feed

  • Question

  • hello i am running an application on two computers 

    it is exactly the same DB is the same 

    everything but the computers is the same !

    i get the next error notice on one machin and not on the other  ????

    "the collection was modified. enumeration operation may not execute"

    is there any thing local that can affect data or structures  in such  way?

    Monday, August 28, 2017 12:14 PM

All replies

  • A lot.

    Basically any insert/delete operation occurs during your foreach loop (or anything that uses IEnumerable<T>/IEnumberable interface) will case the error to be thrown. Commonly found when doing insert/delete logic on collection with need to compare to the target.

    If your application would need to do such action during enumeration, do it with for loop with index instead, and do it in backward order (i.e.: start with "element count - 1", down to "0", with counter--) so the index for element won't change while you insert/deleting.

    Tuesday, August 29, 2017 1:32 AM
  • Hi giladc,

    Thank you for posting here.

    The error occurs under many possibilities. 

    Something like that you could not alter a collection when using an enumerator or else the enumerator becomes invalid.  If you want to remove items from a collection then use a for loop starting at the last index and moving towards the front.  That way removing an item does not affect the indices of the items you are yet to visit. 

    According to your description, we could not confirm where cause the error. Could you provide the code which could produce the error for us to test?

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, August 29, 2017 6:39 AM