I have a Dictionary
.
EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references
In your example, you can not do what you want to do!
You will get a System.InvalidOperationException with a message of Collection was modified; enumeration operation may not execute.
Here is an example to prove:
using System.Collections.Generic;
using System;
public class Test
{
private Int32 age = 42;
static public void Main()
{
(new Test()).TestMethod();
}
public void TestMethod()
{
Dictionary myDict = new Dictionary();
myDict[age] = age.ToString();
foreach(KeyValuePair pair in myDict)
{
Console.WriteLine("{0} : {1}", pair.Key, pair.Value);
++age;
Console.WriteLine("{0} : {1}", pair.Key, pair.Value);
myDict[pair.Key] = "new";
Console.WriteLine("Changed!");
}
}
}
The output would be:
42 : 42
42 : 42
Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
at Test.TestMethod()
at Test.Main()