Article ID: 555972 - Last Review: October 13, 2007 - Revision: 1.0 InvalidOperationException when removing items in a collectionSUMMARYYou receive an InvalidOperationException with the following error message: Collection was modified: enumeration operation may not execute. SYMPTOMSWhen you iterate a collection and remove items in the collection, you receive an InvalidOperationException with the following error message: Collection was modified: enumeration operation may not execute. CAUSECode iterating a collection cannot modify the collection because the run-time makes certain assumptions about the size of the collection. RESOLUTIONyou can work around the limitation by creating a new collection dynamically to hold the enumerated collection. Here is the complete code. using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication { class Program { static void Main(string[] args) { System.Collections.ArrayList arr = new System.Collections.ArrayList(); arr.Add("1"); arr.Add("2"); arr.Add("3"); /*This throws an exception foreach (string s in arr) { arr.Remove(s); } */ //where as this works correctly Console.WriteLine(arr.Count); foreach (string s in new System.Collections.ArrayList(arr)) { arr.Remove(s); } Console.WriteLine(arr.Count); Console.ReadKey(); } } } MORE INFORMATIONThis link http://msdn2.microsoft.com/en-us/library/system.collections.ienumerator(vs.71).aspx discusses the limitation in further detail. It is important to note that the code does not remove the restriction on iterating a collection. Instead, the code simply moves the restriction from one container (arr) to the other (ArrayList).
COMMUNITY SOLUTIONS CONTENT DISCLAIMERMICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES. | Article Translations
|

Back to the top
