Carolyn Van Slyck

When should I implement GetHashCode, Equals, IEquatable and IComparable?

  • GetHashCode and Equals

    I am implementing another equality or comparison interface, I want LINQ set operations to work (e.g. Union, Intersect, Except) or will be using Object.Equals. When I implement anything equality related, this is the first task. I always override GetHashCode and Equals together, never just one or the other.

  • Equality Operators

    I am using the equals (==) or not equals (!=) operators on my objects and I want to compare equality, not references.

  • IEquatable<T>

    I am using my object in a List<T> or Dictionary<T> so that Contains, IndexOf, Remove, etc works.

  • IComparable

    I need to sort my objects, either manually or via List.Sort or LINQ's OrderBy. I prefer to implement the generic IComparable<T> interface over plain old IComparable.