Export (0) Print
Expand All
2 out of 4 rated this helpful - Rate this topic

Guidelines for Implementing Equals and the Equality Operator (==)

The following rules outline the guidelines for implementing the Equals method and the equality operator (==):

  • Implement the GetHashCode method whenever you implement the Equals method. This keeps Equals and GetHashCode synchronized.
  • Override the Equals method whenever you implement ==, and make them do the same thing. This allows infrastructure code such as Hashtable and ArrayList, which use the Equals method, to behave the same way as user code written using ==.
  • Override the Equals method any time you implement the IComparable Interface.
  • You should consider implementing operator overloading for the equality (==), not equal (!=), less than (<), and greater than (>) operators when you implement IComparable.
  • Do not throw exceptions from the Equals or GetHashCode methods or the equality operator (==).

For related information on the Equals method, see Implementing the Equals Method.

Implementing the Equality Operator (==) on Value Types

In most programming languages there is no default implementation of the equality operator (==) for value types. Therefore, you should overload == any time equality is meaningful.

You should consider implementing the Equals method on value types because the default implementation on System.ValueType will not perform as well as your custom implementation.

Implement == any time you override the Equals method.

Implementing the Equality Operator (==) on Reference Types

Most languages do provide a default implementation of the equality operator (==) for reference types. Therefore, you should use care when implementing == on reference types. Most reference types, even those that implement the Equals method, should not override ==.

Override == if your type is a base type such as a Point, String, BigNumber, and so on. Any time you consider overloading the addition (+) and subtraction (-) operators, you also should consider overloading ==.

See Also

Design Guidelines for Class Library Developers | Implementing the Equals Method | Object.Equals Method

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.