2

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?

Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62

1 Answers1

1

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.";
    }
}
Tim Rutter
  • 4,549
  • 3
  • 23
  • 47
  • Thank you very much. I've really lost sight of the call to the overloaded Console.WriteLine(Object) method. This is the reason that the Object's ToString() method was called. – retrograde.su Dec 10 '17 at 08:31