Reputation: 7750
what is the best practice to overload == operator that compares two instances of the same class when it comes to null reference comparison?
MyObject o1 = null;
MyObject o2 = null;
if (o1 == o2) ...
static bool operator == (MyClass o1, MyClass o2)
{
// ooops! this way leads toward recursion with stackoverflow as the result
if (o1 == null && o2 == null)
return true;
// it works!
if (Equals(o1, null) && Equals(o2, null))
return true;
...
}
What is the best approach to handle null references in comparison ?
Upvotes: 5
Views: 1089
Reputation: 1209
This is approach I follow:
http://msdn.microsoft.com/en-us/library/336aedhh.aspx
Upvotes: 2
Reputation: 45252
I've wondered if there is a "best approach". Here's how I do it:
static bool operator == (MyClass o1, MyClass o2)
{
if(object.ReferenceEquals(o1, o2)) // This handles if they're both null
return true; // or if it's the same object
if(object.ReferenceEquals(o1, null))
return false;
if(object.ReferenceEquals(o2, null)) // Is this necessary? See Gabe's comment
return false;
return o1.Equals(o2);
}
Upvotes: 11
Reputation: 18286
if (ReferenceEquals(o1, null) && ReferenceEquals(o2, null))
return true;
etc
Upvotes: 1