[Mono-dev] System.Collections.Generic.Dictionary`2 bug?

Stefan Noack noackstefan at googlemail.com
Fri Feb 1 09:30:10 EST 2008


Hi,

I got he following problem: When i change the values of a Dictionary`2
enumerating the keys i get an exception. for example:

Dictionary<string,int> test = new Dictionary<string,int> ();

test.Add ("foo", 2);
test.Add ("bar", 3);

foreach (string key in test.Keys) {
	test [key] = 5;
}

throws:

System.InvalidOperationException : out of sync
at System.Collections.Generic.Dictionary`2
+Enumerator[System.String,System.Int32].VerifyState () [0x00000]
at System.Collections.Generic.Dictionary`2
+Enumerator[System.String,System.Int32].MoveNext () [0x00000]
at System.Collections.Generic.Dictionary`2+KeyCollection
+Enumerator[System.String,System.Int32].MoveNext () [0x00000]

It looks like the KeyCollection enumerator uses the Enumerator of the
Dictionary which might invalidate when i change the values, but is this
intended? 

MSDN says:

«The foreach statement is a wrapper around the enumerator, which allows
only reading from the collection, not writing to it.»

So do i have to understand this in the way that i am also not allowed to
change the values ehen enumerating the keys?

If it is a bug, please tll me i will then try to fix it, if not i will
change my code to use a copy of the key list or something.

--
Stefan Noack




More information about the Mono-devel-list mailing list