Junior — Middle
Why is it important to override the GetHashCode method in classes?
sobes.tech AI
Answer from AI
Overriding the GetHashCode method is important for the correct functioning of objects in hash-based collections such as Dictionary, HashSet, and others.
Reasons:
GetHashCodereturns a numeric value used for quick object lookup in hash tables.- If two objects are considered equal (by the
Equalsmethod), they should return the same hash code so that collections handle them correctly. - If
GetHashCodeis not overridden along withEquals, objects may be compared incorrectly or duplicated in collections.
Example:
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, overriding GetHashCode ensures consistency with Equals and proper functioning of objects in hash structures.