syven
syven

Reputation: 1

C# comparing int and long as object

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

Upvotes: 0

Views: 618

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 191058

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

Upvotes: 0

Related Questions