Why C# doesn't support base.base?

2.1k views Asked by At

I tested code like this:

class A
{
    public A() { }

    public virtual void Test ()
    {
        Console.WriteLine("I am A!");
    }
}

class B : A
{
    public B() { }

    public override void Test()
    {
        Console.WriteLine("I am B!");
        base.Test();
    }
}

class C : B
{
    public C() { }

    public override void Test()
    {
        Console.WriteLine("I am C!");
        base.base.test(); //I want to display here "I am A"
    }
}

And tried to call from C method Test of A class (grandparent's method). But It doesn't work. Please, tell me a way to call a grandparent virtual method.

2

There are 2 answers

3
Jon Skeet On

You can't - because it would violate encapsulation. If class B wants to enforce some sort of invariant (or whatever) on Test it would be pretty grim if class C could just bypass it.

If you find yourself wanting this, you should question your design - perhaps at least one of your inheritance relationships is inappropriate? (I personally try to favour composition over inheritance to start with, but that's a separate discussion.)

0
Bala R On

One option is to define a new method in B as shown below

class B : A
{
    public B() { }

    public override void Test()
    {
        Console.WriteLine("I am B!");
        base.Test();
    }

    protected void TestFromA()
    {
        base.Test()
    }
}

and use TestFromA() in C