Suppose we have defined two classes (A and B):
class A
{
public new virtual string ToString()
{
return "I'm class A object.";
}
}
class B : A
{
public override string ToString()
{
return "I'm class B object.";
}
}
If we write:
A a = new B();
Console.WriteLine(a);
"B" (namespace.B) will be displayed in the console.
That is, the ToString() method of an implicit ancestor of Class A (System.Object.ToString()) will be called.
Why is calling a method of the System.Object class, not class A or B?
Firstly, if you do this:
It writes out the two strings you want.
The new means you have to explicitly call
ToStringfrom anAinstance. Hencea.ToString()works.((object)a).ToString()does not.By calling
Console.WriteLine(a), you are calling theConsole.Writeline(object)overload. As a result theWriteLinefunction is making use of anobjectreference therefore you get the defaultobject.ToString().Make it override in both cases and the problem goes away (i'm guessing you already know this):