Above is a partial screen shot from Visual Studio 2015 while debugging some c# code. CachedList[2][uniqueColumn.Name] is an int and its value is 3, value is also an in and its value is also 3, however when I compare the two I get the wrong result. How can this be?
-
20Because they are boxed as `object` you're getting reference comparison and not value comparison. – juharr Sep 27 '18 at 15:50
-
https://stackoverflow.com/questions/814878/c-sharp-difference-between-and-equals – gunnerone Sep 27 '18 at 15:58
-
Yes that is the solution. I need to use .Equals() rather than ==. – tdinpsp Sep 27 '18 at 20:42
1 Answers
This is due to the fact that the integers are boxed ('wrapped' in objects), and the compare for objects does a compare-by-reference: are they the same object in memory, answer: no.
If you want to compare them by value, and you know that both are always int
(and you want to make this explicit in your code), then you can use typecasting to unbox and ==
to compare:
var isEqual = (int)CachedList[2][uniqueColumn.Name] == (int)value;
(see .NET Fiddle: https://dotnetfiddle.net/z3lwBG)
If the type inside the two objects isn't always int
, but you know or assume they are the exact same type, then you can use .Equals()
:
var isEqual = CachedList[2][uniqueColumn.Name].Equals(value);
Note, this may still not always give the desired result. If one is a boxed int
and the other is e.g. a boxed long
, then - because the types are different - Equals()
will return false
, even if the values themselves might be considered equal, as in (object)3
vs (object)3L
. Equals()
does not even try to compare the values in such a case.

- 22,460
- 5
- 32
- 69
-
-
Actually gunnerone has the solution that works for me. I don't want to cast to an int because the code must also handle string, long, DateTime, etc. So I'm using object1.Equals(object2) rather than object1 == object2. – tdinpsp Sep 27 '18 at 20:44
-