I have a base class with a long chain of inheritance. I pass around instances of a child class in a variable with the type of the base class. Can I do a ToString on the instance of the child class and have the child's ToString run (not the parents)?
Here is my attempt:
namespace Abc
{
class A
{
string strA = "A";
public virtual string ToString() { return strA; }
}
class B : A
{
string strB = "B";
public virtual string ToString() { return base.ToString() + strB; }
}
class C : B
{
string strC = "C";
public virtual string ToString() { return base.ToString() + strC; }
}
class Program
{
static void Main(string[] args)
{
A a = new C();
System.Console.WriteLine(a.ToString());
System.Console.ReadLine();
}
}
}
This program outputs A
. I thought that adding the virtual
keyword would have it output ABC
. How can I get this result without casting? Casting requires me to know the type at compile time.