#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;
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #406 – Overriding the Equals Method

  1. JakeIL7 says:

    “When you override Equals, you should also override GetHashCode”

    Why?

    • Sean says:

      Good question. You’re anticipating tomorrow’s post, which is already written and just waiting to be published– “Why You Should Override GetHashCode When Overriding Equals”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: