Very Smart .NET Collections Exception

I can’t recall how many times I’ve had to pick my brain figuring out why code wasn’t working due to a Collection changing while I was enumerating with it in Java. .NET just threw a very cool exception when executing:

foreach(string key in DeltaQueue.Keys)
{
if(((DequeueInfoSet)DeltaQueue[key]).DequeueBehavior.DequeueNow())
DeltaQueue.Remove(key);
}

The exception was:

An unhandled exception of type ‘System.InvalidOperationException’ occurred in mscorlib.dll

Additional information: Collection was modified; enumeration operation may not execute.

Very cool exception! Right there, at runtime, that has saved me I’m sure a few hours in debugging.

Leave a Reply

Your email address will not be published. Required fields are marked *