-1

enter image description here

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?

Lennart
  • 9,657
  • 16
  • 68
  • 84
tdinpsp
  • 160
  • 6

1 Answers1

4

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.

Peter B
  • 22,460
  • 5
  • 32
  • 69