Overloading == in C#

When overriding the == operator on immutable objects, I’ve previously done something akin to

public static bool operator ==(MyThing x, MyThing y)
{
    // Null tests
    try {var ignore =  x.GetType(); } // Provoke NRE
    catch(NullReferenceException)
    {
        try
        {
            var ignore = y.GetType();
            return false; // Only one operand null
        }
        catch (NullReferenceException)
        {
            // Both operands null
            return true;
        }               
    }
    return x.Equals(y);
}

to catch the case of two null objects. (null == null) should evaluate to true. Equals, of course, evaluates if the fields of the objects are identical. However, this solution purposefully raises an exception and then catches it, which is never a good design, and also makes debugging with “break on all exceptions” a pain. So I was quite happy when I realized that the test could be written as

public static bool operator ==(MyThing x, MyThing y)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(x, y))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)x == null) || ((object)y == null))
    {
        return false;
    }

    // Return true if the fields match:
    return x.Equals(y);
}

instead. I can’t take any credit for the solution above, since it’s lifted almost verbatim from Microsoft’s C# Programming Guide, Guidelines for Overloading Equals() and Operator ==. But that’s the way it always is, any information you want is always out there on the net somewhere, you just need to find it. Hopefully this post helps someone else do just that.