Sobes.tech
Junior — Middle

How does the GetHashCode method affect the operation of a dictionary in .NET?

sobes.tech AI

Answer from AI

The GetHashCode method in .NET is used to obtain the hash code of an object, which is used in hash tables, such as dictionaries (Dictionary<TKey, TValue>).

When you add an object to a dictionary, GetHashCode is called first to determine the bucket for storage. When searching for an object, the dictionary uses the hash code for quick access.

It is important that:

  • If two objects are equal (by the Equals method), their hash codes should match.
  • If hash codes differ, the objects are considered different.

Incorrect implementation of GetHashCode can lead to the dictionary being unable to find a key even if it exists, or to decreased performance due to a high number of collisions.

An example of a correct implementation:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Person other)
            return Name == other.Name && Age == other.Age;
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
}

Thus, GetHashCode affects the correctness and efficiency of the dictionary's operation.