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

Interfaces:
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.
E.g.:
If Equals == true then
x.GetHashCode() == y.GetHashCode()
GetHashCode() is frequently used by collections like Dictionary<Key, Value> and HashSet<T>

Links:
Guidelines for Overloading Equals() and Operator == (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms173147.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *