c# - Marking ToString virtual in base class, what happens? -
consider following (linqpad) example. tostring in class x marked virtual. why output here not equal "hi, i'm y, hi, i'm x" instead typename printed? of course marking tostring virtual wrong, because defined in object virtual, trying understand happening here.
void main() { y y = new y(); console.writeline(y); } // define other methods , classes here class x { public virtual string tostring() { return "hi, i'm x"; } } class y : x { public override string tostring() { return "hi, i'm y, " + base.tostring(); } }
that's creating new virtual method in x
called tostring()
hides object.tostring()
. if have:
y y = new y(); x x = y; object o = y; console.writeline(y.tostring()); // shows "hi, i'm y, hi, i'm x"; console.writeline(x.tostring()); // shows "hi, i'm y, hi, i'm x"; console.writeline(o.tostring()); // calls object.tostring; shows "y"
calling just
console.writeline(y);
is equivalent final line, why type name printed.
basically, x.tostring
method should override object.tostring()
method:
public override string tostring() { return "hi, i'm x"; }
Comments
Post a Comment