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!