Search code examples
c#genericsinterfacecovariance

Result type covariance - generic class with method returning both an interface type and a specific type


I've got these 2 interfaces:

public interface IResult
{
    object SomeProperty {get;set;}
}

public interface IFooManager
{
    IResult GetResult(string someId);
}

I'd like to implement an IFooManager in a generic class this way:

public class MyFooManager<T> : IFooManager where T: class, IResult
{
    public T GetResult(string id)
    {
        return null; //the value doesn't really matter here
    }
}

However, this results in a compilation error:

Cannot implement method from interface [..].IFooManager. Return type should be [..].IResult

Now, I know I could solve this by additionally defining the interface method explicitly, like this:

IResult IFooManager.GetResult(string id)
{
    return GetResult(id);
}

But the questions is: why can't the compiler just figure it out, that T GetResult() indeed returns an object implementing IResult? I know I could probably introduce an out T covariance interface on top of that, but I can't scratch it out of my head - why is the T type restriction not enough to ensure type safety?


Solution

  • Because:

    IResult GetResult(string someId);
    

    is not the same as:

    T GetResult(string id)
    

    You told the compiler with the constraint that T is any class implementing IResult - not IResult. These 2 things are not the same.