C# comparing int and long as object

417 views Asked by At

If 2 variables of the type "object", which are Int32 and Int64, are compared, "true" is displayed in Visual Studio. If I save this in a variable, it suddenly changes to "false". I have already tried the EqualityComparer. The values remain unchanged.

int number1 = 2;
long number2 = 2;
object object1 = number1;
object object2 = number2;
var equals1 = number1 == number2; // true
var equals2 = object1 == object2; // object1 == object2 is true, equals2 is false

screenshot

Why is that?

EDIT:

updated screenshot

1

There are 1 answers

4
Daniel A. White On

This is because you implicitly boxed the variables into the heap, which create new references, which is why equals2 is false.