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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With