Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading operator== and comparison to null

I've got a class that overloads the operator== to compare two objects, however when I check an object of that type against null, then I get a null-reference exception on the first parameter. I wondered how I should guard against such a case, or is there another way to implement this operator==

Card c;

if (c == null) { // do something }  //null check throws exception cause c1 in operator has is a null object...

 public static bool operator ==(Card c1, Card c2)
        {
            if (ReferenceEquals(c1, null) )
                return false; // this does not make sense either I guess??
            return c1.Equals(c2);
        }
like image 273
Tony The Lion Avatar asked Dec 01 '22 03:12

Tony The Lion


1 Answers

The ReferenceEquals check should do it; actually, a cheeky route can be:

if(((object)c1) == ((object)c2)) return true;
if(((object)c1) == null || ((object)c2) == null) return false;
return c1.Equals(c2);

The (object) casts are essentially NOPs, and just force it to perform a reference check instead of recursively hitting ==, but also without an extra static call to ReferenceEquals.

like image 197
Marc Gravell Avatar answered Dec 03 '22 18:12

Marc Gravell