3

Given the following two interfaces:

public interface IFoo{}
public interface IBar
{
    IFoo Foo { get; }
}

The following generic class implements the IBar interface.

public class Implementation<T> : IBar where T : IFoo
{
    public T Foo { get; }
    IFoo IBar.Foo => Foo;
}

Why is IFoo IBar.Foo => Foo; even necessary and is there a more elegant solution?

Of course, I could change the property Foo of the Implementation class to IFoo to get rid of the generic type. But in my application, I have other classes inheriting from the Implementation class. Those deriving classes define a specific type for the generic T : IFoo argument. For example something like:

public class Child : Implementation<FooImplementation>
{
}

public class FooImplementation : IFoo { }
jasdefer
  • 757
  • 12
  • 24
  • This is a form of return type covariance. More discussion [here](https://stackoverflow.com/questions/5709034/does-c-sharp-support-return-type-covariance). There are also issues in the [compiler repo](https://github.com/dotnet/roslyn/issues/357) and the [language repo](https://github.com/dotnet/csharplang/issues/49). – Mike Zboray Apr 06 '18 at 07:36
  • Should you be able to achieve what you want by defining your `IBar` interface as `IBar` and your property as `T Foo { get; }`? So in your implementation class you can do: `public class Implementation : IBar where T : IFoo`. This will then allow you to have a property `public T Foo { get; }` . – ragyaiddo Apr 06 '18 at 07:54
  • @mikez thanks for the info. – jasdefer Apr 06 '18 at 08:19
  • @ragyaiddo I still have the same problem with your suggested approach. – jasdefer Apr 06 '18 at 08:21

0 Answers0