4

I have a class that I want to overload the == operator for in c#. I already have a .Equals override that works properly. When I tried to use my == operator, it gave me a null reference exception on my object (Person). If I try to check if it is null, it will in turn call the same operator to check it against null and create an infinite loop. This seems like a huge flaw and I can't figure out the right way to do it.

public static bool operator ==(Person person, object obj)
{
    return person == null ? person.Equals(obj) : false;
}

public static bool operator !=(Person person, object obj)
{
    return !(person == obj);
}
svick
  • 236,525
  • 50
  • 385
  • 514
viper110110
  • 85
  • 1
  • 8
  • Shouldn't it be return person != null ? person.Equals(obj) : false; – vc 74 May 29 '13 at 20:17
  • When comparing to `null`, you should use `!object.ReferenceEquals(person, null)` to ensure (and make clear!) that you're checking for reference equality. – dlev May 29 '13 at 20:20
  • 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:10

1 Answers1

9

Use (object)person == null to force it to use the == operator of Object (or use ReferenceEquals). See http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx.

Ryan M
  • 2,072
  • 11
  • 14
  • A 3rd option would be to use the static `object.Equals(person, null)` method. – Servy May 29 '13 at 20:27
  • 1
    @Servy: Though that works, that's taking advantage of an implementation detail of `object.Equals`. Calling `ReferenceEquals` always does the right thing and is easy to read and understand, so that would be my preferred solution. – Eric Lippert May 30 '13 at 00:30
  • @EricLippert Can you call it an implementation detail if it's [documented](http://msdn.microsoft.com/en-us/library/w4hkze5k.aspx) as such? “It determines whether the two objects represent the same object reference. If they do, the method returns `true`. This test is equivalent to calling the `ReferenceEquals` method. In addition, if both `objA` and `objB` are `null`, the method returns `true`.” Though I agree that `ReferenceEquals()` is clearer. – svick May 30 '13 at 12:51
  • @svick: You make a good point; you can rely upon object.Equals to do reference equality first. – Eric Lippert May 30 '13 at 13:45
  • 1
    Oh my god, Eric Lippert commented on my answer. I don't even care if he was replying to someone else's comment. I'm going to take the rest of the day off. – Ryan M May 30 '13 at 14:09