I was playing around with Dictionary and stumbled across the below scenario
public class MyObject
{
public string I { get; set; }
public string J { get; set; }
public string K { get; set; }
public override int GetHashCode()
{
int hashCode = (I+J+K).GetHashCode();
Debugger.Log(9, "INFO", hashCode.ToString() + System.Environment.NewLine);
return hashCode;
}
}
class Program
{
static void Main(string[] args)
{
MyObject obj1 = new MyObject() { I = "Hello", J = "World" };
MyObject obj2 = new MyObject() { I = "Hello", J = "World" };
Dictionary<MyObject, string> collection = new Dictionary<MyObject, string>();
collection.Add(obj1, "1");
var result = collection[obj2]; // KeyNotFound exception here.
}
}
I have MyObject class which acts as a key to dictionary and I override the GetHashCode method to return hash code based on the values stored in the class.
So, when the above code is executed, both obj1 and obj2 returns same hash code, but still the dictionary throws KeyNotFound exception.
Any reason why such a behavior?