I have the following code snippet
Class Parent
{
public override String ToString()
{
return "in Parent";
}
public virtual void printer()
{
Console.write(this.ToString());
}
}
Class Child : Parent
{
public override String ToString()
{
return "in Derived";
}
public override void printer()
{
base.printer();
Console.write(this.ToString());
}
}
in Main I have
Parent p = new Derived();
p.printer();
The output comes as “In Derived” 2 times. This is expected as most overridden method is called.
But, is it possible to call the ToString() method of the base class, in this case instead of the base calling the derived one?
No. Form MSDN:
So even if you cast to
Parent, the object is still aChildso that override will apply. The problem is that you’re callingToString()from the parent class which has been overridden, so there’s no way to get to it if the instance is aChild.One way to get around it is to create a separate private function instead of using
ToString():