Tony The Lion
Tony The Lion

Reputation: 63310

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);
        }

Upvotes: 4

Views: 2632

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064204

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.

Upvotes: 15

Emond
Emond

Reputation: 50712

See these guidelines From that page:

Overloaded operator == implementations should not throw exceptions.

Upvotes: 4

Related Questions