overloading operator== and comparison to null
I've got a class that overloads the operator==
to compare two objects, however when I check an开发者_Python百科 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);
}
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
.
See these guidelines From that page:
Overloaded operator == implementations should not throw exceptions.
精彩评论