Just sharing some of my inconsequential lunch conversations with you... RSS  

Friday, February 15, 2008

System.InvalidOperationException: Collection was modified

Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

This is documented as:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. For example, InvalidOperationException is thrown by:

  • MoveNext if objects of a collection are modified after the enumerator is created.

Argh, sometimes enumerators are just too conservative. This seems to be the case:

    Hashtable hashTable = new Hashtable();

hashTable.Add(1, 1.ToString());
hashTable.Add(2, 2.ToString());
hashTable.Add(3, 3.ToString());

foreach (object key in hashTable.Keys)
{
hashTable[key] = "something else";
}

To solve this, all we have to do is to get another collection to iterate:

 foreach (object key in new ArrayList(hashTable.Keys))

Though understanding this behavior, the responsibility of this sanity check could probably be delegated optionally to the programmer. In my sample I am not changing the enumeration, just the value. Lets not forget that the new ArrayList solution depends upon memory usage.

No comments:

Development Catharsis :: Copyright 2006 Mário Romano