c# - Overriding Equals and type casting -
in following example third evaluation returns false, good, fourth example returns true..
don't quite understand how works however, default object.equals
compares 2 references object equality, , seeing a
, b
both point unique instance of string, should return false, in third example not in fourth.
understand why returns true in 2nd example seeing .equals()
method overridden in string class, in fourth example we're casting string object.
wouldn't call object.equals
in case?
static void main() { // create 2 equal distinct strings string = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); console.writeline (a == b); // returns true console.writeline (a.equals(b)); // returns true // let's see happens same tests // variables of type object object c = a; object d = b; console.writeline (c == d); // returns false console.writeline (c.equals(d)); // returns true }
the clue words "by default". string
overrides object.equals
custom implementation. since object.equals
polymorphic method (virtual
/ override
/ etc), most-derived implementation gets used if variable (/expression) type object
.
==
, however, not polymorphic; implementation used depends entirely on variable (/expression) type. in case, since known type object
, comparison available reference equality.
perhaps more succinctly:
class foo { public override string tostring() { return "hi"; } } //... object obj = new foo(); string s = obj.tostring(); // "hi"
this same principle: derived overload of virtual method used, regardless of type compiler knows (object
in case).
Comments
Post a Comment