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:
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
It writes out the two strings you want.
The new means you have to explicitly call ToString
from an A
instance. Hence a.ToString()
works. ((object)a).ToString()
does not.
By calling Console.WriteLine(a)
, you are calling the Console.Writeline(object)
overload. As a result the WriteLine
function is making use of an object
reference therefore you get the default object.ToString()
.
Make it override in both cases and the problem goes away (i'm guessing you already know this):
class A
{
public override string ToString()
{
return "I'm class A object.";
}
}
class B : A
{
public override string ToString()
{
return "I'm class B object.";
}
}