The issue is that OtherType<T>
is a class and generic classes do not allow co/contravariance in C#. Generic interfaces
do, as long as out
types do not appear in any input positions, and in
types do not appear in any output positions. In your code sample, you could get it to compile by introducing an additional interface marked covariant, and then altering your return type.
public interface IOtherType<out T> {} // new
public class OtherType<T> : IOtherType<T> { }
public interface IInterface<T>
{
IOtherType<IInterface<T>> Operation(); // altered
}
public class Impl : IInterface<int>
{
public IOtherType<IInterface<int>> Operation()
{
return new OtherType<Impl>();
}
}
Whether or not this would actually fit your use case with your additional method definitions is something only you can know, given the limited about of detail in your code snippet.