0

This is what I could come up with to check for null equality. It works but it is Shreak looking. The following is valid for this example:

x != null and y == null returns false;
x == null and y != null returns false;
x == null and y == null returns true;
x.ToString() == y.ToString() returns true;

I guess I could code the above but I still feel there is a cleaner way to solve it.

public bool Equals(ConvertibleData x, ConvertibleData y)
{
    if (x == null)
    {
        if (y == null)
        {
            return true;
        }

        return false;
    }

    if (y == null)
    {
        return false;
    }

    return x.ToString() == y.ToString(); //Disregard the ToString, this coult be any comparer validation
}
RollRoll
  • 8,133
  • 20
  • 76
  • 135

3 Answers3

5

I usually use this pattern where the comparands can be null:

public bool Equals(ConvertibleData? x, ConvertibleData? y)
{
    if (ReferenceEquals(x, y))
        return true;

    if (x is null || y is null)
        return false;

    return x.ToString() == y.ToString(); //Disregard the ToString, this coult be any comparer validation
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
2

I like this pattern:

if (x is null && y is null)
    return true;
if (x is null || y is null);
    return false;

// Check x's properties against y's properties
canton7
  • 37,633
  • 3
  • 64
  • 77
0

All your answers are better than code in the question above. I found this example from the official microsoft reference website about IEqualityComparer:

link

public bool Equals(Box b1, Box b2)
{
    if (b2 == null && b1 == null)
       return true;
    else if (b1 == null || b2 == null)
       return false;
    else if(b1.Height == b2.Height && b1.Length == b2.Length
                        && b1.Width == b2.Width)
        return true;
    else
        return false;
}
RollRoll
  • 8,133
  • 20
  • 76
  • 135