Junior — Middle
Why should the GetHashCode method be overridden in a class?
sobes.tech AI
Answer from AI
The GetHashCode method is used to obtain the hash code of an object, which is used in hash tables, such as in Dictionary or HashSet collections. It should be overridden if you override the Equals method to ensure consistency: objects considered equal by Equals should have the same hash code. This is important for the correct functioning of hash-based collections.
Example:
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);
}
}