tags:

views:

743

answers:

7

The following will cause infinite recursion on the == operator overload method

    Foo foo1 = null;
    Foo foo2 = new Foo();
    Assert.IsFalse(foo1 == foo2);

    public static bool operator ==(Foo foo1, Foo foo2) {
        if (foo1 == null) return foo2 == null;
        return foo1.Equals(foo2);
    }

How do I check for nulls?

+6  A: 

Cast to object in the overload method:

public static bool operator ==(Foo foo1, Foo foo2) {
    if ((object) foo1 == null) return (object) foo2 == null;
    return foo1.Equals(foo2);
}
Andy J
+15  A: 

Use ReferenceEquals:

Foo foo1 = null;
Foo foo2 = new Foo();
Assert.IsFalse(foo1 == foo2);

public static bool operator ==(Foo foo1, Foo foo2) {
    if (object.ReferenceEquals(null, foo1))
        return object.ReferenceEquals(null, foo2);
    return foo1.Equals(foo2);
}
Abe Heidebrecht
+3  A: 

Try Object.ReferenceEquals(foo1, null)

Anyway, I wouldn't recommend overloading the == operator; it should be used for comparing references, and use Equals for "semantic" comparisons.

Santiago Palladino
+1  A: 

Use ReferenceEquals. From the MSDN forums:

public static bool operator ==(Foo foo1, Foo foo2) {
    if (ReferenceEquals(foo1, null)) return ReferenceEquals(foo2, null);
    if (ReferenceEquals(foo2, null)) return false;
    return foo1.field1 == foo2.field2;
}
Mufasa
A: 

You can try to use an object property and catch the resulting NullReferenceException. If the property you try is inherited or overridden from Object, then this works for any class.

public static bool operator ==(Foo foo1, Foo foo2)
{
    //  check if the left parameter is null
    bool LeftNull = false;
    try { Type temp = a_left.GetType(); }
    catch { LeftNull = true; }

    //  check if the right parameter is null
    bool RightNull = false;
    try { Type temp = a_right.GetType(); }
    catch { RightNull = true; }

    //  null checking results
    if (LeftNull && RightNull) return true;
    else if (LeftNull || RightNull) return false;
    else return foo1.field1 == foo2.field2;
}
The Digital Gabeg
A: 

@The Digital Gabeg: If you have many null objects then exception handling may be a big overhead.

Kasprzol
Haha, I agree that this is not the best method. After posting this method, I immediately revised my current project to use ReferenceEquals instead. However, despite being suboptimal it does work, and thus is a valid answer to the question.
The Digital Gabeg
+1  A: 

When I want the operator == and Foo.Equals(object obj) to return the same answer, I usually implement the != operator like this: public static bool operator ==(Foo foo1, Foo foo2) { return object.Equals(foo1, foo2); } public static bool operator !=(Foo foo1, Foo foo2) { return !object.Equals(foo1, foo2); }

The operator == will then after doing all the null checks for me end up calling foo1.Equals(foo2) where I do the actually checking is the two are equal.

Hallgrim