I have read that when you override Equals on an class/object you need to override GetHashCode.
public class Person : IEquatable
{
In your scenario, not overriding GetHashCode
on your type will affect only the first dictionary, as the key is what's used for hashing, not the value.
When looking for the presence of a key, the Dictionary
will use the hash code to find out if any keys could be equal. It's important to note that a hash is a value that can determine if two things could be equal or very likely are equal. A hash, strictly speaking cannot determine if two items are equal.
Two equal objects are required to return the same hash code. However, two non-equal objects are not required to return different hash codes. In other words, if the hash codes don't match, you're guaranteed that the objects are not equal. If the hash codes do match, then the objects could be equal.
Because of this, the Dictionary
will only call Equals
on two objects if their hash codes match.
As to "how to override GetHashCode
", that's a complicated question. Clasically, a hashing algorithm should provide a balance between even distribution of the codes over the set of values with a low collision rate (a collision is when two non-equal objects produce the same code). This is a simple thing to describe and a very difficult thing to accomplish. It's easy to do one or the other, but hard to balance them.
From a practical perspective (meaning disregarding performance), you could just XOR
all of the characters of the first and last names (or even use their respective hash codes, as Joel suggests) as your hash code. This will give a low degree of collision, but won't result in a terribly even distribution. Unless you're dealing with very large sets or very frequent lookups, it won't be an issue.