Home > front end >  Define protected abstract interface method as abstract in abstract class
Define protected abstract interface method as abstract in abstract class

Time:10-12

I have an interface like this

interface IFoo
{
    protected abstract int Compute();
    int ComputeValue()
    {
        return Compute();
    }
}

The idea being that Compute computes some value and ComputeValue maybe does some checks and then calls Compute to fetch the actual value. However, I now wonder how to implement this interface in an abstract class. I can do it like this

abstract class Bar : IFoo
{
    public abstract int Compute();
}

but I dont want Compute to be called directly. However, when I try to implement it explicitly, e.g.

abstract class Bar : IFoo
{
    abstract int IFoo.Compute();
}

I cannot define it as abstract in the abstract class Bar, which is what I want. Of course, I could do something like

abstract class Bar : IFoo
{
    protected abstract int Compute();

    int IFoo.Compute()
    {
        return Compute();
    }
}

But I wonder is there a more elegant way of doing this without the additional extra method?

CodePudding user response:

Not much you can do here. Though according to draft spec it was considered at some point to allow the support for explicit interface abstract overrides in classes (also see the reabstraction part):

Because we support explicit abstract overrides in interfaces, we could do so in classes as well

abstract class E : IA, IB, IC // ok
{
    abstract void IA.M();
}

Open issue: should we support explicit interface abstract overrides in classes?

But it seems it was not followed through - see LDM-2019-03-27 Notes:

Explicit interface abstract overrides in classes
Allow abstract interface implementions in a class as well? Not an abstract class method implementing an interface method.

So either remove the Compute from the interface or use your current approach.

  • Related