See the code below.
static void Main(string[] args)
{
// Create Dictionary
var dict = new Dictionary<TestClass, ValueClass>();
// Add data to dictionary
CreateSomeData(dict);
// Create a List
var list = new List<TestClass>();
foreach(var kv in dict) {
// Swap property values for each Key
// For example Key with property value 1 will become 6
// and 6 will become 1
kv.Key.MyProperty = 6 - kv.Key.MyProperty + 1;
// Add the Key to the List
list.Add(kv.Key);
}
// Try to print dictionary and received KeyNotFoundException.
foreach (var k in list)
{
Console.WriteLine($"{dict[k].MyProperty} - {k.MyProperty}");
}
}
static void CreateSomeData(Dictionary<TestClass, ValueClass> dictionary) {
dictionary.Add(new TestClass {MyProperty = 1}, new ValueClass {MyProperty = 1});
dictionary.Add(new TestClass {MyProperty = 2}, new ValueClass {MyProperty = 2});
dictionary.Add(new TestClass {MyProperty = 3}, new ValueClass {MyProperty = 3});
dictionary.Add(new TestClass {MyProperty = 4}, new ValueClass {MyProperty = 4});
dictionary.Add(new TestClass {MyProperty = 5}, new ValueClass {MyProperty = 5});
dictionary.Add(new TestClass {MyProperty = 6}, new ValueClass {MyProperty = 6});
}
Key and Value Class:
namespace HashDictionaryTest
{
public class TestClass
{
public int MyProperty { get; set; }
public override int GetHashCode() {
return MyProperty;
}
}
}
namespace HashDictionaryTest
{
public class ValueClass
{
public int MyProperty { get; set; }
public override int GetHashCode() {
return MyProperty;
}
}
}
I am using the dotnet core 2.2 on Ubuntu. I did this test out of curiosity only. However, to my surprise, I got KeyNotFoundException.
I expected to receive the wrong values. However, I received the exception as mentioned above.
What I want to know is, why we got this error? What is the best practice in generating the HashCode so that we can avoid such issues?