Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define protected abstract interface method as abstract in abstract class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading