when i cast int and float to object and compare them the equality is always false. Why?
float f = 0.0f;
int i = 0;
Console.WriteLine(f.Equals(i)); // true
Console.WriteLine(i.Equals(f)); // false
Console.WriteLine(i == f); // true
Console.WriteLine("----------------");
object obf = f;
object obi = i;
Console.WriteLine(obf.Equals(obi)); // false
Console.WriteLine(obi.Equals(obf)); // false
Console.WriteLine(obi == obf); // false
Console.WriteLine("----------------");
Update:
this is NOT the case for the same type
int i1 = 1;
int i2 = 1;
object oi1 = i1;
object oi2 = i2;
Console.WriteLine(oi1.Equals(oi2)); // true
Console.WriteLine(oi2.Equals(oi1)); // true
A
floatis only equal to anotherfloat, and anintis only equal to anotherint. The only lines which are returningtrueare these ones:In both of these cases, there’s an implicit conversion of the value of
itofloat, so they’re equivalent to:These conversions are just normal conversions required for overload resolution of methods and operators.
None of the rest of the lines involve that implicit conversion, so they’re comparing the two different types, which gives a result of
falseeven when it is comparing by value (which is the case with all theEqualscalls). That’s why usingEqualson the boxedintvalues does returntrue, because that’s comparing two values of the same type, by value.In this case:
it’s not even trying to compare numeric values – it’s comparing the references for the boxed objects. As there are two different references, the result is
false– and would be even if both values were of typeint.