Why does == not work while comparing two object type variables boxed with same int value

前端 未结 3 470
难免孤独
难免孤独 2021-01-18 06:57

While trying to implement a simple singly linked list in C#, I noticed that == does not work while comparing two object type variables boxed with an int value b

3条回答
  •  不思量自难忘°
    2021-01-18 07:25

    It's because the System.Object implementation of == tests reference equality, like the static Equals(object, object), while instance Equals(object) is overloaded, so it checks the actual value.

    When you box a value type twice, you get two different instances, so of course reference equality fails.

    The operator, being static, is bound at compile time, so there is no dynamic dispatch. Even with strings, which are already reference types and are therefore not boxed when assigned to an object-type variable, you can get an unintended reference comparison with the == operator if one of the operands has a static type other than string.

提交回复
热议问题