Why is 0L not equal to 0 when clicking on an object?

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

Can someone explain this?

 0L.Equals(0) // true ((object)0L).Equals(0L) // true ((object)0L).Equals(0) // false 
+5
source share
3 answers

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

MSDN :

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

+13
source
 ((object)0L).Equals(0) 

here you are comparing the type of the object with the type int (dont quote me on int may be a different numeric type)

types are different.

0
source
 0L.Equals(0) // true 

This enables the long.Equals method, which takes a long parameter as a parameter. The actual expression for the parameter is indicated by int . That int implicitly converted to long , so long 0 is passed, which is equal to another value.

 ((object)0L).Equals(0L) // true ((object)0L).Equals(0) // false 

The long box here prevents overloading long.Equals and leaves only overloading object.Equals , which takes an object parameter. Since the object parameter is both fragments, each of which has long and int respectively, both are obtained in a box. The object.Equals implementation also checks the type of the parameter and considers that any objects of different types are not equal. The first of these two fragments skips the check, after which it continues to check the values, considering them equal. In the second fragment there is no check, the result is false .

0
source

Source: https://habr.com/ru/post/1210696/


All Articles