Código hash en Diccionario <TKey, TValue>
Estaba jugando con Dictionary y me topé con el siguiente escenario
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.
}
}
Tengo la clase MyObject que actúa como una clave para el diccionario y anulo el método GetHashCode para devolver el código hash en función de los valores almacenados en la clase.
Entonces, cuando se ejecuta el código anterior, obj1 y obj2 devuelven el mismo código hash, pero aún así el diccionario arroja la excepción KeyNotFound.
¿Alguna razón por qué tal comportamiento?