Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET C# Explicit implementation of grandparent's interface method in the parent interface

That title's a mouthful, isn't it?...

Here's what I'm trying to do:

public interface IBar {
     void Bar();
}
public interface IFoo: IBar {
    void Foo();
}
public class FooImpl: IFoo {
    void IFoo.Foo()   { /* works as expected */ }
    //void IFoo.Bar() { /* i'd like to do this, but it doesn't compile */ }

    //so I'm forced to use this instead:
    void IBar.Bar()   { /* this would compile */ }
}

My problem with this is that it's... inconvenient to call Bar():

IFoo myFoo = new FooImpl();
//myFoo.Bar(); /* doesn't compile */
((IBar)myFoo).Bar(); /* works, but it's not necessarily obvious 
                        that FooImpl is also an IBar */

So... Is there a way to declare IFoo.Bar(){...} in my class, other than basically merging the two interfaces into one?

And, if not, why?

like image 567
Cristian Diaconescu Avatar asked Dec 21 '10 16:12

Cristian Diaconescu


People also ask

What is .NET C#?

C# (pronounced "See Sharp") is a modern, object-oriented, and type-safe programming language. C# enables developers to build many types of secure and robust applications that run in . NET. C# has its roots in the C family of languages and will be immediately familiar to C, C++, Java, and JavaScript programmers.

Is .NET similar to C++?

C++ is a object oriented programming language. But here . Net is a framework which supports multiple languages to build applications using . net class libraries which will be excueted via CLR .

What is .NET language?

NET is a free, cross-platform, open source developer platform for building many different types of applications. With . NET, you can use multiple languages, editors, and libraries to build for web, mobile, desktop, games, IoT, and more.

What is C# mainly used for?

What is C# used for? Like other general-purpose programming languages, C# can be used to create a number of different programs and applications: mobile apps, desktop apps, cloud-based services, websites, enterprise software and games. Lots and lots of games.


2 Answers

It's possible to use the new keyword in an interface to explicitly hide a member declared in the interface it extends:

public interface IBar
{
    void Bar();
}

public interface IFoo:IBar
{
    void Foo();
    new void Bar();
}

public class Class1 : IFoo
{
    void Bar(){}

    void IFoo.Foo(){}

    void IFoo.Bar(){}

    void IBar.Bar(){}
}
like image 100
Grokodile Avatar answered Oct 11 '22 20:10

Grokodile


You don't have two implementations of IFoo; you only have one.
The CLR does not distinguish between copies of interfaces that come from different points in the interface tree.

In particular, there is no way to call IFoo.Bar(); you can only call IBar.Bar.
If you add a separate Bar() method to IFoo, your code will work.

like image 29
SLaks Avatar answered Oct 11 '22 20:10

SLaks