Why does GetHashCode () matter?

I am trying to understand what object.GetHashCode() . I read that it is used by collections to uniquely identify keys. But I wanted to check it, and the result is not the one I expected.

 struct Animal { public string Name { get; set; } public int Age { get; set; } public Animal(string name, int age) : this() { Name = name; Age = age; } public override int GetHashCode() { return Age.GetHashCode(); } } object doggy = new Animal("Dog", 25); object cat = new Animal("Cat", 25); Hashtable table = new Hashtable(); table.Add(doggy, "Dog"); table.Add(cat, "Cat"); Console.WriteLine("{0}", table[cat]); Console.WriteLine("{0}", table[doggy]); 

I would expect “Cat” to overwrite “Dog” or some kind of error, telling me that “key already exists”, but the output

"Cat dog"

+6
c #
source share
2 answers

GetHashCode is only the first test used to determine imbalance and possible equality. After that Equals is checked. For objects, reference equality is used by default, and for structures, a comparison in half is used. Override Equals to give an appropriate implementation (paired with a hash code), and it should give the expected results (duplicate key).

btw, the IDE probably already gives you a warning that GetHashCode and Equals should always be processed together ...

+12
source share

Hash codes are used as the first check for dividing objects into groups. If the collection contains the hash code of each element in it, it can search for the element by first looking at the elements whose hash code matches the value of the element being searched. Once he finds one or more of these items, he can study them in more detail. Ideally, objects that are not equal will always return different hash codes, but this is impractical. If objects that are not equal return identical hash codes, you may need to examine them all in detail at any time when you look for one of them.

+2
source share

All Articles