With ==
operator I can do this:
int a = 10;
int b = 10;
a==b //true
In this case C# makes a compile-time decision, and no virtual behavior comes into play.
But, if I use:
object a = 10;
object b = 10;
a == b //false
The result is false because object
is a class (reference type) and a
and b
each refer to different boxed objects on the heap.
To solve it I should do:
object a = 10;
object b = 10;
a.Equals (b) // True
Because Equals
is a virtual method and it is resolved at runtime depending of the objects’s actual type.
My question is:
Why the designers of C# didn’t avoid the problem by making == virtual, and so functionally identical to Equals?
Because ==
is a static
method, so cannot be virtual. This was probably done to better handle null
.
Note that your dilemma has nothing to do with boxing, C# uses the compile time type of both parameters to determine what overload* of ==
makes sense. For instance, take the following example.
object s1 = "Hello";
object s2 = new String('H', 'e', 'l', 'l', 'o');
s1 == s2; //False
(string)s1 == (string)s2; //True
* Overload is not absolutely correct, since we are searching more than one class hierarchy, but it is close enough semantically for the discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With