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 the equality operator (==), 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 the equality operator.
Override the Equals method any time you implement the IComparable.
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 about 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 the equality operator (==) 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 the equality operator (==) 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 the equality operator (==) on reference types. Most reference types, even those that implement the Equals method, should not override the equality operator (==).
Override the equality operator (==) 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 the equality operator (==).
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.
See Also
Reference
Implementing the Equals Method