Overriding the Equals Method

You can override the Equals method in a custom type to implement value equality for two instances of the type.
Guidelines to follow when overriding Equals include:
  • x.Equals(x) should return true
  • x.Equals(y) should return the same value as y.Equals(x)
  • x.Equals(y) and y.Equals(z) implies that x.Equals(z)
  • Repeated calls to x.Equals(y) return the same result, for the same values of x and y
  • x.Equals(null) returns false
Additionally:
  • When you override Equals, you should also override GetHashCode
Here’s the implementation of Equals for the Dog class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Are two Dogs equivalent?
public override bool Equals(object obj)
{
    // Can't be null
    if (obj == null)
        return false;
 
    // Must be a Dog
    if (obj is Dog)
    {
        // Compare the dogs
        Dog d2 = (Dog)obj;
        return (Name == d2.Name) && (Age == d2.Age);
    }
    else
        return false;
}
Here’s the override of GetHashCode.


1
2
3
4
public override int GetHashCode()
{
    return Name.GetHashCode() ^ Age;
}