Can anyone explain why Item1 == Item2
of this Tuple<object,object>
evaluates to false when both Item1
and Item2
are both the boolean value false
?

- 5,279
- 4
- 27
- 59
-
3I note that `if (x == y) return true; else return false;` could be written much more easily as `return x==y;` – Eric Lippert Mar 12 '17 at 04:00
-
See marked duplicate. The comparison you are making is of the _references_ of the boxed values, not the values themselves. Same issue the OP in the marked duplicate had. See his own resolution, i.e. use `Equals()`, and answers to his question, for alternatives that will do what you want. – Peter Duniho Mar 12 '17 at 05:23
-
@PeterDuniho Thank you. I didn't really know what to search for, but I can see that the root cause is identical – Matt Thomas Mar 12 '17 at 13:47
2 Answers
The problem is the way ==
works since it does't traverses the hierarchy tree and simply uses the type of the value (because it is not a virtual overridable method but an operator instead), which is boxed so Object, that functions by reference check, so if they aren't the exact same object (not value) it will return false.
As you yourself said in your answer they got boxed to an object. Therefore to fix this, you can use Equals
which fixes your problem as C# goes to the topmost child of the value (which in your case would be Boolean.Equals
instead of operator ==
from Object):
var allEqual = together.All(tuple => tuple.Item1.Equals(tuple.Item2));

- 640
- 1
- 9
- 27
I'm pretty sure it's because of Boxing. The Tuple
's items are both object
s, so the ==
operator is performing a reference comparison. Since Item1
gets boxed into a different object
than Item2
, the ==
reference comparison returns false.

- 5,279
- 4
- 27
- 59