The code demo is outlined here: https://dotnetfiddle.net/mCm8Hx
If I have a class that overrides Equals
and operators ==
and !=
, I can compare them via variables typed as that class.
But if I cast them to object
(or use variables typed as object that are assigned to instances of that class), the operator doesn't seem to be used anymore.
Eg this would work:
var a1 = new MyClass(5);
var a2 = new MyClass(5);
Console.WriteLine(a1 == a2); // prints "true" because I've implemented == operator
This also works ( MySubClass: MyClass
):
var b1 = new MySubClass(10);
var b2 = new MySubClass(10);
Console.WriteLine(b1 == b2); // prints "true" because I've implemented == operator in inherited class MyClass
But this doesn't:
object o1 = a1;
object o2 = a2;
Console.WriteLine(o1 == o2); //prints "false", doesn't use my operator implementation
Since all classes inherit implicitly from Object
, I'd expect it to work the same way as it works with MySubClass
. Why this isn't the case with object
typed vars?
First of all let's look at the Object class itself:
As you can see the Equals method has virtual
key on it, meaning that in any class that inherits from object, if you override
that method, then even if your variable object o2 = a2;
is typeof object pointing to new instance of A
class -> this method will be invoked by the runtime:
public override bool Equals(object other)
On the other hand the operator ==
is not virtual
, it cannot be overriden, so when referring to object
variable it will always resolve to System.Object.ReferenceEquals
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.