Friday, September 14, 2007

overloading operator==


Beware of infinite recursion when overloading the == operator!


When you overload the equality operator (==) in C#, you should of course remember that:

  • you should also overload operator !=

  • the operator's implementation should not throw exceptions


  • Having to overload the unequality operator (!=) as well is rather obvious. Saying:
    a != b
    is another way of saying:
    !(a == b)

    The second point is not unusual, either. No one would rather expect an operator to throw an exception - otherwise, you'd have to put every other if statement in a try-catch block.

    And what would you actually do with a "CouldNotCheckForEqualityException" anyway? It's not a kind of error you'd expect at runtime, is it? If you can't check two objects for equality - you would rather like to know that at compile time!


    Now - in order to protect yourself from throwing an exception in the implementation of the == operator, you should check its arguments for being null, so that you can safely access their fields for comparison purposes.

    Oh, that's simple, isn't it?
    if (x == null)
    return y == null;
    else
    return x.Equals(y);

    Pretty clever, eh? But this will NOT work, unfortunately!
    Note that the two comparisons to null will actually call the overloaded == operator, causing an infinite recursion!

    There are actually two ways of fixing that:

  • you could call x.ReferenceEquals(null) - not too elegant for me, or
  • you could cast the arguments to objects:
    if ((object) x == null)
    return (object) y == null;
    else
    return x.Equals(y);

    And that's what I call a really clever and slick piece of code :)
    Thanks go to the author of this post for sharing it:
    Re: Overloading operator== and comparing to null

    Oh, and of course the implementation of the != operator would be:
    return !(x == y)
  • No comments: