Orace
Orace

Reputation: 8359

How to call a base method that is declared as abstract override

In C# it's possible to mark a virtual method abstract to force inherited class to implement it.

class A
{
    public virtual void Method()
    {
        Console.WriteLine("A method call");
    }
}

abstract class B : A
{
    // Class inherited from B are forced to implement Method.
    public abstract override void Method();
}

I would like to call the A implementation of Method from a class inherited from B.

class C : B
{
    public override void Method()
    {
        // I would like to call A implementation of Method like this:
        // base.base.Method();
    }
}

The best way I find to do this is to add a protected method "MethodCore" in A implementation and call it when needed.

class A
{
    public virtual void Method()
    {
        MethodCore();
    }

    protected void MethodCore()
    {
        Console.WriteLine("A method call");
    }
}

abstract class B : A
{
    public abstract override void Method();
}

class C : B
{
    public override void Method()
    {
        MethodCore();
    }
}

Is there any other way to do this ?

Upvotes: 2

Views: 7232

Answers (1)

Chetan Kinger
Chetan Kinger

Reputation: 15212

The best way I find to do this is to add a protected method "MethodCore" in A implementation and call it when needed.

Yes. Since you can't call an abstract method using base, all possible solutions are going to require you to eventually call Method in A using an A instance.

That said, it looks like you are looking for a way to provide a default implementation of Method in B such that any subclass of B that does not implement the method should simply use the implementation present in A. A better solution would be to not mark Method as abstract in B. Instead, make Method in B redirect to Method in A using base.Method()

abstract class B : A {
// Class inherited from B are forced to implement Method.
   public virtual void Method() { 
        base.Method()//calls Method in A
   }
}

This way, any subclass of B that wants to call Method from A can simply say base.Method().

Upvotes: 2

Related Questions