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
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
.