Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overload == (and != , of course) operator, can I bypass == to determine whether the object is null

when I try to overload operator == and != in C#, and override Equal as recommended, I found I have no way to distinguish a normal object and null. For example, I defined a class Complex.

public static bool operator ==(Complex lhs, Complex rhs)
{
    return lhs.Equals(rhs);
}

public static bool operator !=(Complex lhs, Complex rhs)
{
    return !lhs.Equals(rhs);
}

public override bool Equals(object obj)
{
    if (obj is Complex)
    {
        return (((Complex)obj).Real == this.Real &&
                   ((Complex)obj).Imaginary == this.Imaginary);
    }
    else
    {
        return false;
    }
}

But when I want to use

if (temp == null)

When temp is really null, some exception happens. And I can't use == to determine whether the lhs is null, which will cause infinite loop.

What should I do in this situation.

One way I can think of is to us some thing like Class.Equal(object, object) (if it exists) to bypass the == when I do the check.

What is the normal way to solve the problem?

Thank you.

like image 559
LLS Avatar asked Jun 09 '10 12:06

LLS


2 Answers

You can use the following at the top of your Equals override:

if (Object.ReferenceEquals(obj, null))
    return false;

The exception you are getting is probably a StackOverflowException because your == operator will cause infinite recursion.

EDIT:

If Complex is a struct you should not have any problems with NullReferenceExceptions. If Complex is a class you can change your implementation of the == and != operator overloads to avoid the exception (Laurent Etiemble already pointed this out in his answer):

public static bool operator ==(Complex lhs, Complex rhs)
{
    return Equals(lhs, rhs);
}

public static bool operator !=(Complex lhs, Complex rhs)
{
    return !Equals(lhs, rhs);
} 
like image 74
Jakob Christensen Avatar answered Oct 22 '22 06:10

Jakob Christensen


You should consider using the static Equals method in the operator overloads (which will call the instance Equals method):

public static bool operator ==(Complex lhs, Complex rhs)
{
    return Equals(lhs, rhs);
}

public static bool operator !=(Complex lhs, Complex rhs)
{
    return !Equals(lhs, rhs);
}

Note: You may also check for null in the Equals method.

You can also read the Object.Equals Topic on MSDN, which is a great source of samples.

like image 31
Laurent Etiemble Avatar answered Oct 22 '22 07:10

Laurent Etiemble