views:

505

answers:

3

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.

+1  A: 

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

Ray
+2  A: 

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;
        }
    }
}
280Z28
A: 

The protected member FooBase.Bar() is not an implementation method of the interface IBar. The interface demands a public Method Bar().

There are 2 ways implementing an interface. Explicit implementation or implicit implementation.

Following is explicit implementation. This method is called if an object of Foo is called through a IBar variable.

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

Defining a public method Bar() is implicit implementation.

To have the compiler satisfied you might override or new the baseclass method as public (not a good advise, if method is protected in baseclass).

new public bool Bar() 
{
    return base.Bar();
}

The trick is to implement an interface, but not having all interface members as public members in the class.

Christian13467