Finding items in dictionary is based on hash code. The hash code is based on item id in below code so I shouldn't change item id. But I have done some experiment and I have changed item id and searched it in dictionary but then I have got KeyNotFoundException. Could somebody explain me why?
After change point1 id, it has 1727699806 hash code, element with index 0 in dictionary has the same hash code: 1727699806 - so why I have KeyNotFoundException?
class Program
{
public class Point
{
public int Id { get; set; }
public override bool Equals(object obj)
{
return obj is Point point &&
Id == point.Id;
}
public override int GetHashCode()
{
return HashCode.Combine(Id);
}
}
static void Main(string[] args)
{
Point point1 = new Point();
point1.Id = 5;
Point point2 = new Point();
point2.Id = 20;
var dictionary = new Dictionary<Point, string>()
{
{ point1, "Poland" },
{ point2, "Germany" }
};
point1.Id = 999; // here I change id
var point1_hash = point1.GetHashCode(); //1727699806
var dictionary1_hash = dictionary.ElementAt(0).Key.GetHashCode(); //1727699806
var dictionary2_hash = dictionary.ElementAt(1).Key.GetHashCode(); //650208270
string result = dictionary[point1]; //KeyNotFoundException
}
}
After change point1 id, it has 1727699806 hash code, element with index 0 in dictionary has the same hash code: 1727699806 - so why I have KeyNotFoundException?