I found another big gotcha in .NET today. When iterating over a Hashtable, you might want to change something within that Hashtable, like say change or clear out a value. Ain't gonna happen, buddy. Nice big runtime exception: Collection was modified; enumeration operation may not execute
.
I got it the first time and I slapped my forehead—figuratively, of course, as I'm not in the habit of self-flagellation. So I did what I always do. *sigh* I got clever. I thought that I could obviate the problem by enumerating through the Hashtable.Keys
collection and make my changes that-a-way.
Again, no dice. I'm not entirely sure how changing the value of a Hashtable key while looping over a collection of keys is affecting the underlying Hashtable. But I think it has something to do with the CLR iterating over the Keys collection by reference rather than by value.
The answer, after some Googling, is to split the operation into two phases: storing the keys to be changed in another collection and then looping over that second store to actually modify the values or do what-have-you. It's decidedly not as elegant as say creating an isolating enumeration class, but I've got work to do.