-
foreach Dictionary
Hello everyone,
If we use foreach to iterate a Dictionary, it is only restricted that we can not insert new elements and remove exsting elements of the Dictionary.
And we are free (allowed) to change the content (mmber fields) of object pointed by the "value" reference of a key, right? Example,
Code:
foreach (KeyCollection<> k in someDictionary)
{
// some operation will change the member fields of related object instance
// pointed by "value" refernece of the related key k
someDictionary[k].someOperation();
}
thanks in advance,
George
-
If you iterate over all keys, then get the value from the dictionary to do some operation on it, why don't you get all values in the first place ?
And yes, only changing the container will break the iterator, manipulating the contents will not. As there is no const-correctness in C# and the compiler does not know which statement changes an objects state and which does not, foreach would have no use otherwise.