1

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?

jokul
  • 1,269
  • 16
  • 37
  • possible duplicate of [How do I check for nulls in an '==' operator overload without infinite recursion?](http://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion) – Sam Jan 19 '14 at 04:06

2 Answers2

3

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));
Sam
  • 40,644
  • 36
  • 176
  • 219
2

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);
   }
}
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • @Ben Voigt: Thanks for your comment. I get that ReferenceEquals implementation from the book CLR via C#. http://books.google.com.vn/books/about/CLR_Via_C.html?id=7yb-QQAACAAJ&redir_esc=y . I'm not sure if that is correct or I missed something when reading. – Khanh TO Jan 19 '14 at 04:41