Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C#) Problems when overloading the == operator [duplicate]

I overloaded the == operator on my class as follows:

public static bool operator ==(Table pt1, Table pt2) {
    return Compare(pt1, pt2) == 0 && pt1.TableName == pt2.TableName;
}

Compare will work just as the strcmp does in c++, returning an integer. Problem is that if I do an if (MY_CLASS == null), it will call my == operator, and thus my Compare function. What is the alternatiev? to put an check on pt1 and pt2 to see if they are null? Or just in pt2?

like image 350
Jorge Branco Avatar asked Dec 01 '22 07:12

Jorge Branco


2 Answers

You should checkout Microsoft's guidelines for implementing the '==' operator and also for overriding 'Equals()'.

Adapting their example you'd want something like:

public static bool operator ==(Table a, Table 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 Compare(a, b) == 0 && a.TableName == b.TableName;
}
like image 152
Luke Quinane Avatar answered Dec 05 '22 02:12

Luke Quinane


You will need the null checks to get the correct behaviour. The clearest way to add this check in my opinion is to call object.ReferenceEquals(x, null), since it is a straight non-polymorphic method call and presumably fairly efficient.

like image 43
jerryjvl Avatar answered Dec 05 '22 01:12

jerryjvl