Monday, September 06, 2010

Equality in C#

Here is a good article on the subject.

I wish, I wish, I wish that C# had ditched nulls and default reference equality; that's such a 1960s resource limited way of thinking.  Equality should mean structural equality by default; one should have to explicitly ask for reference equality or nullable types.

Oh well, here's the summary:

  • Implement IEquatable.Equals(T).
    • Remember to check for null and reference equality.
  • Override object.Equals(object).
  • object.Equals(object, object) does what you expect by first testing for nulls and reference equality.
  • Override object.GetHashCode.
  • If you implement == (reference equality by default), also implement !=.
  • Implement the == and != operators for value types to avoid the need for boxing.

No comments: