I can\'t understand, why the if
statement in the picture below returns false.
I hope you can explain it to me.
You can see, that the values and the typs
The ==
operator you are calling is the overload that takes two object
parameters. This uses reference equality - the value isn't important, it has to be the same object.
As you can read in the documentation:
For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.
While int
is a value type, it has been 'boxed' (wrapped in an object
). You are comparing the two different reference types that wrap your integers.
To fix this, you can use object.Equals
instead - this will compare the two integers.
item.Equals(value);
Or the static method (which would handle the case where item == null
):
object.Equals(item, value);
If you unbox to int
then you can use the int
overload of ==
as you expect:
(int)item == (int)value;
Again, per the docs:
For predefined value types, the equality operator (==) returns true if the values of its operands are equal.