Overload operator == and comparison with null

I have a class that overloads operator== to compare two objects, however, when I check an object of this type for null , then I get an exception using a NULL reference for the first parameter. I wondered how I should defend 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); } 
+4
source share
2 answers

Checking ReferenceEquals should do this; in fact, the sassy route could be:

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

The (object) drives are essentially NOPs and simply force it to perform a check instead of a recursive hit == , but also without an additional static call to ReferenceEquals .

+14
source

See these recommendations from this page:

The overloaded operator == implementation should not throw exceptions.

+4
source

Source: https://habr.com/ru/post/1340482/


All Articles