Working with Equals() and GetHashCode() to compare your objects in C#

In general these interfaces and methods are good to implement when working with comparing objects of the same type in C#:

System.IEquatable<T> – strongly typed implementation
IComparable<T> – strongly typed implementation

Override methods:
An override of Object.Equals(Object).
An override of Object.GetHashCode().
An override of Object.ToString() is usually a good idea.
Operator overloads for operator == and operator !=.

General rule of GetHashCode():
If two objects is equal then their hashvalues should be the same.
If Equals == true then
x.GetHashCode() == y.GetHashCode()
GetHashCode() is frequently used by collections like Dictionary<Key, Value> and HashSet<T>

Guidelines for Overloading Equals() and Operator == (C# Programming Guide)

Leave a Reply