jokul
jokul

Reputation: 1339

Overloading == and != operator, need to determine if object null without infinite recursion

I want to extend the == operator for my object. It is a simple overload, just checking to see if the properties for two objects are all identical:

if(x == null && y == null)
{
    return true;
}
return  x != null && y != null
        && x.GetType() == y.GetType()
        && x.GetType()
            .GetProperties()
            .All(property => property.GetValue(x) == property.GetValue(y));

I'm sure most people will see the problem: the == operator is being overridden and thus an infinite recursion occurs on line 1. How can I check to see if x and y are null without recursively calling the == operator?

Upvotes: 1

Views: 89

Answers (2)

Khanh TO
Khanh TO

Reputation: 48992

Another solution is casting to object and then use == operator.

if((object)x == null && (object)y == null)
{
    return true;
}
return  !((object)x == null) && !((object)y == null) //or (object)x != null && (object)y != null
        && x.GetType() == y.GetType()
        && x.GetType()
            .GetProperties()
            .All(property => property.GetValue(x) == property.GetValue(y));

Actually, under the hood, when we call Object.ReferenceEquals, the parameters are cast into objects and perform ==. Here is how Object.ReferenceEquals is implemented in .NET Framework

public class Object {
    public static Boolean ReferenceEquals(Object objA, Object objB) {
      return (objA == objB);
   }
}

Upvotes: 2

Sam
Sam

Reputation: 42447

I think you should be able to use Object.ReferenceEquals to do this:

if(Object.ReferenceEquals(x, null) && Object.ReferenceEquals(y, null))
{
    return true;
}
return  !Object.ReferenceEquals(x, null) && !Object.ReferenceEquals(y, null)
        && x.GetType() == y.GetType()
        && x.GetType()
            .GetProperties()
            .All(property => property.GetValue(x) == property.GetValue(y));

Upvotes: 3

Related Questions