Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 0L not equal 0 when cast to an object?

Tags:

c#

I don't think I understand why the first statement evaluates to true and the last statement evaluates to false, but it's been a long day.

Can somebody explain it?

0L.Equals(0) // true
((object)0L).Equals(0L) // true
((object)0L).Equals(0) // false
like image 568
ken Avatar asked Jan 08 '15 21:01

ken


People also ask

Is 0 a long value in Java?

You cannot compare them in this way because the new Long(0) returns a reference to a class, not a primitive type.

Can we compare long and long in java?

longs can not be compared with ==. The theory states that you need to use a simple trick like subtracting the one from the other and see the relevant difference.


Video Answer


1 Answers

Object.Equals first compares the types if the object is a value type which it is. Both are different in this case.

MSDN:

If the current instance is a value type, the Equals(Object) method tests for value equality. Value equality means the following: The two objects are of the same type. As the following example shows, a Byte object that has a value of 12 does not equal an Int32 object that has a value of 12, because the two objects have different run-time types.

like image 143
Tim Schmelter Avatar answered Oct 19 '22 06:10

Tim Schmelter