Junior — Middle
How are the Equals and GetHashCode methods related in object-oriented programming?
sobes.tech AI
Answer from AI
In C#, the methods Equals and GetHashCode are closely related and are used for object comparison and working with hash tables (e.g., in Dictionary or HashSet).
- The Equals method determines whether two objects are equal in meaning.
- The GetHashCode method returns an integer value (hash code) that should be the same for objects considered equal by Equals.
It is important that if two objects are equal (Equals returns true), their hash codes must match. This is necessary for the correct functioning of hash-based collections.
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);
}
}
Thus, proper implementation of both methods guarantees correct behavior of objects in collections and during comparison.