Junior — Middle
What is the purpose of overriding the GetHashCode method in an object?
sobes.tech AI
Answer from AI
Overriding the GetHashCode method in an object is necessary for the correct functioning of hash tables and collections such as Dictionary or HashSet. This method returns a numerical hash code of the object, which is used for quick lookup and comparison.
If you override the Equals method to compare objects by content, you must also override GetHashCode so that objects considered equal have the same hash code. Otherwise, collections may not work correctly.
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);
}
}
Here, GetHashCode guarantees that two objects with the same Name and Age will have the same hash code.