Sudo Bash
Sudo Bash

Reputation: 433

Using ToString of parent class without cast in c sharp

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.

Upvotes: 0

Views: 2918

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127593

You don't need to declare virtual at each level, you only need to do that in the class that declares it, child classes should do override instead. Because ToString() is defined in Object which is what A is implicitly derived from all off your classes should just use override

class A
{
    string strA = "A";
    public override string ToString() { return strA; }

    //Added a example of somthing not declared in Object
    public virtual string Example() { return "I am in A!"; }
}
class B : A
{
    string strB = "B";
    public override string ToString() { return base.ToString() + strB; }

    //Notice the override instead of the virtual.
    public override string Example() { return "I am in B!"; }
}
class C : B
{
    string strC = "C";
    public override string ToString() { return base.ToString() + strC; }

    public override string Example() { return "I am in C!"; }
}

What was causing your error is you where Shadowing ToString(), you should have gotten a compiler warning telling you that you where doing that and you needed to use the new keyword to get rid of the compiler warning and explicitly state that you wanted to shadow and not override the method.

Upvotes: 6

Related Questions