Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inherited protected method implementing interface

I have this class/interface definitions in C#

public class FooBase {
    ...
    protected bool Bar() { ... }
    ...
}

public interface IBar {
    bool Bar();
}

Now I want to create a class Foo1 derived from FooBase implementing IBar:

public class Foo1 : FooBase, IBar {
}

Is there some class declaration magic that the compiler takes the inherited protected method as the publicly accessible implementation of the interface?

Of course, a Foo1 method

bool IBar.Bar()
{
    return base.Bar();
}

works. I'm just curious whether there is a shortcut ;)

Omitting this method results in a compiler error: Foo1 does not implement interface member IBar.Bar(). FooBase.Bar() is either static, not public, or has wrong return type.

Explanation: I separate code inheritance (class hierarchy) and feature implementation (interfaces). Thus for classes implementing the same interface, accessing shared (inherited) code is very convenient.

like image 348
devio Avatar asked Feb 27 '26 04:02

devio


2 Answers

No shortcut. In fact, this pattern is used in a few places I've seen (not necessarily with ICollection, but you get the idea):

public class Foo : ICollection
{
    protected abstract int Count
    {
        get;
    }

    int ICollection.Count
    {
        get
        {
            return Count;
        }
    }
}
like image 63
Sam Harwell Avatar answered Feb 28 '26 23:02

Sam Harwell


I believe your code is as short as it can be. Don't think there is any kind of shortcut out there.

like image 23
Ray Avatar answered Feb 28 '26 22:02

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!