Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equality operators override (== and !=) [duplicate]

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!

like image 723
Mike Christensen Avatar asked Jan 30 '12 03:01

Mike Christensen


1 Answers

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;
}
like image 172
Kirill Polishchuk Avatar answered Sep 21 '22 01:09

Kirill Polishchuk