1

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?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
AILogic
  • 25
  • 3
  • 2
    Don't put it in the interface, if it is only an implementation detail of the (abstract) class. The interface defines the _public_ contract – knittl Oct 11 '22 at 19:06
  • Given that interfaces can have default methods, I would argue that they define more than just the public contracts. While I would generally agree, in my specific case this is by far the more elegant solution. – AILogic Oct 11 '22 at 19:29
  • Default methods are still part of the _public_ contract, the only difference is that they come with an implementation and can be used as mixins. – knittl Oct 11 '22 at 19:30
  • @AILogic _"Given that interfaces can have default methods, I would argue that they define more than just the public contracts"_ - that's why personally I hugely dislike this feature which was introduced in C# 8 I would argue mainly for the sake of compatibility with java. So I would recommend to avoid using it. – Guru Stron Oct 11 '22 at 19:32

1 Answers1

2

Not much you can do here. Though according toto the 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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132