#406 – 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:

        // 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.

        public override int GetHashCode()
        {
            return Name.GetHashCode() ^ Age;
        }
Advertisement