Junior — Middle
Why override the GetHashCode and Equals methods in a .NET class?
sobes.tech AI
Answer from AI
In .NET, the methods GetHashCode and Equals are overridden for correct object comparison and proper functioning with collections such as dictionaries (Dictionary) and sets (HashSet).
- Equals determines when two objects are considered equal in meaning.
- GetHashCode returns a numeric code used for quick object lookup in hash tables.
If only Equals is overridden but not GetHashCode, objects may not work correctly in hash collections. Usually, these methods are overridden together to ensure consistency: if Equals returns true for two objects, their GetHashCode should return the same value.
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);
}
}