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

Posted by LLS on Stack Overflow See other posts from Stack Overflow or by LLS
Published on 2010-06-09T12:38:38Z Indexed on 2010/06/09 12:42 UTC
Read the original article Hit count: 144

Filed under:
|

Hello, 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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about operator-overloading