Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an interface with interface members

Tags:

c#

interface

What is the proper way to implement an interface that has its own interface members? (am I saying that correctly?) Here's what I mean:

public Interface IFoo
{
    string Forty { get; set; }
    string Two { get; set; }
}

public Interface IBar
{
    // other stuff...

    IFoo Answer { get; set; }
}

public class Foo : IFoo
{
    public string Forty { get; set; }
    public string Two { get; set; }
}

public class Bar : IBar
{
    // other stuff

    public Foo Answer { get; set; } //why doesnt' this work?
}

I've gotten around my problem using explicit interface implementation, but I'm wondering if there is a better way?

like image 994
jstark Avatar asked Dec 05 '25 08:12

jstark


1 Answers

You need to use the exact same type as in the interface:

public class Bar : IBar 
{ 
    public IFoo Answer { get; set; }   
} 

Note: IFoo instead of Foo.

The reason is that the interface defines a contract and the contract says that it must be an IFoo.

Think about it:

You have the classes Foo and Foo2, both implement IFoo. According to the contract, instances of both classes can be assigned. Now, if your code was legal, this would somehow break because your class only accepts Foo. Explicit interface implementation doesn't change that fact in any way.

like image 71
Daniel Hilgarth Avatar answered Dec 07 '25 20:12

Daniel Hilgarth



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!