Wednesday, January 18, 2017

How to solve "Collection was modified; enumeration operation may not execute." in Dictionary iteration using C#

when i try to iterate through a dictionary and remove the item that had been processed.

i got a runtime error "Collection was modified; enumeration operation may not execute."

Dictionary<string, FileAttachement> tempAttachment = attachments;
tempAttachment.Remove(item.Key);

the root cause of the error is that i declause a temp variable and reference to the same objec that will iterate through. the run time process detect the change of the attachments object and throw the exeption.

we can't simply use the variable with referenced to dictionary object. we should use the deep copy or clone mechanism to get a copy of the dictionary object.

the following snipet of code will create a new object and copy the content from the dictionary object.

Dictionary<string, FileAttachement> tempAttachment = new Dictionary<string, FileAttachement>(attachments);



No comments:

Post a Comment