Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle null when writing equals operator [duplicate]

Possible Duplicate:
How do I check for nulls in an '==' operator overload without infinite recursion?

When I overload the == operator for objects I typically write something like this:

    public static bool operator ==(MyObject uq1, MyObject uq2) {
        if (((object)uq1 == null) || ((object)uq2 == null)) return false;
        return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2;
    }

If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?

like image 454
George Mauer Avatar asked Sep 17 '08 19:09

George Mauer


3 Answers

As Microsoft says,

A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead results in a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.

So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe).

So yes, it seems there should be a better way, but the method you use is the one recommended.

However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.

like image 123
Philip Rieck Avatar answered Nov 04 '22 21:11

Philip Rieck


ReferenceEquals(object obj1, object obj2)

like image 45
Juanma Avatar answered Nov 04 '22 23:11

Juanma


@neouser99: That's the right solution, however the part that is missed is that when overriding the equality operator (the operator ==) you should also override the Equals function and simply make the operator call the function. Not all .NET languages support operator overloading, hence the reason for overriding the Equals function.

like image 2
Scott Dorman Avatar answered Nov 04 '22 23:11

Scott Dorman