What is the purpose of overriding the equals method in a class?
sobes.tech AI
Answer from AI
Overriding the Equals method in a C# class is necessary to define the logic for comparing objects for equality based on their content, rather than their reference.
By default, the Equals method compares object references (i.e., checks whether two variables point to the same object in memory). However, it is often necessary to compare the contents of objects — for example, considering two objects with identical field values as equal.
By overriding Equals, you specify what it means for your objects to be "equal." Usually, this is done together with overriding GetHashCode to ensure correct behavior in hash-based collections (such as Dictionary or HashSet).
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);
}
}
This approach allows comparing Person objects based on their content rather than their reference.