Junior — Middle
What is the role of the GetHashCode method when using a dictionary or hash collection?
sobes.tech AI
Answer from AI
The GetHashCode method plays a key role when using dictionaries and other hash collections in C#. It returns an integer value (hash code) that is used for quickly determining the position of an object in a hash table.
When you add an object to a dictionary, GetHashCode is called first to determine the bucket where the element will be placed. When searching for an element by key, the hash code is also calculated first to quickly find the needed bucket, and then Equals is called for an exact comparison.
It is important that:
- If two objects are equal (Equals returns true), their GetHashCode should return the same value.
- Well-distributed hash codes reduce the number of collisions and improve performance.
Example of overriding:
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);
}
}