I have a problem with inheritance.

I have the class A with functions x and y
Class B is a subclass of A and should override y. y should call y in A and add extra functionality.
Class C is a subclass of B and should override y. y should call y in B and add extra functionality.
When I create an instance of C x should call the version of y defined in C.

If I get this right I need to declare y in B as "virtual" to be able to override it in C. I also need to declare it "override" to be able to override y in A. But "virtual" and "override" can not be combined!
I can't use "new" either because that would make x call the wrong version of y.

What have I missunderstood here? There must be a way to do this.

Recommended Answers

All 2 Replies

You will not need to specify virtual in B to override it in C. The virtual of A will cascade, essentially. Run the following sample:

using System;

class Program
{
    static void Main()
    {
        C c = new C();
        c.Y();

        Console.Read();
    }
}

class A
{
    public void X()
    {
        this.Y();
    }

    public virtual void Y()
    {
        Console.WriteLine("A.Y()");
    }
}

class B : A
{
    public override void Y()
    {
        Console.WriteLine("B.Y()");
        base.Y();
    }
}

class C : B
{
    public override void Y()
    {
        Console.WriteLine("C.Y()");
        base.Y();
    }
}

C.Y() will print "C.Y()" to the screen and then call the base, which will be B.Y(). Same thing, print to screen, then base (A.Y()).

Interestingly, and this was just posted today, but Eric Lippert of the C# team wrote that if you had a situation where C was compiled into C.dll and it inherited from B in B.dll, which inherited from A in A.dll, and C overrode Y() and B did not, then obviously the base call to Y() refers to A.Y(). If you later got a newer version of B.dll that included an override of Y(), C would not call it unless it was recompiled. The reason is that the base call is evaluated at compile time, not runtime. It's an interesting scenario.

http://blogs.msdn.com/ericlippert/archive/2010/03/29/putting-a-base-in-the-middle.aspx

commented: well constructed example and a really interesting link too +1

Thanks, I knew there had to be an easy way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.