Possible Duplicate:
How do I check for nulls in an ‘==’ operator overload without infinite recursion?
I have an object that looks like this:
public class Tags
{
int mask;
public static bool operator !=(Tags x, Tags y)
{
return !(x == y);
}
public static bool operator ==(Tags x, Tags y)
{
return x.mask == y.mask;
}
}
This works fine for comparing instances to each other, but I also want to be able to handle an expression such as:
if(tags1 == null)
Doing this causes an exception on the following line:
return x.mask == y.mask;
Since y
is null
.
I've tried changing this function to:
public static bool operator ==(Tags x, Tags y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.mask == y.mask;
}
However, this creates a stack overflow since the implementation uses its own overridden comparison operator.
What's the trick to getting the ==
operator to handle comparisons to null
? Thanks!
According to guideline:
public static bool operator ==(Tags a, Tags b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.mask == b.mask;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With