-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?

3
  • 20
    Because they are boxed as object you're getting reference comparison and not value comparison. Commented Sep 27, 2018 at 15:50
  • stackoverflow.com/questions/814878/… Commented Sep 27, 2018 at 15:58
  • Yes that is the solution. I need to use .Equals() rather than ==. Commented Sep 27, 2018 at 20:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Maybe worth mentioning .Equals
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.
Included .Equals and how it behaves.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.