Tadeusz
Tadeusz

Reputation: 6913

Why C# doesn't support base.base?

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.

Upvotes: 9

Views: 2214

Answers (2)

Bala R
Bala R

Reputation: 109037

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

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1504182

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.)

Upvotes: 14

Related Questions