Search code examples
c#genericsinterface

Why can't this generic method return concrete class that implements it's interface?


I would like to return the concrete class 'CountryPage' from this method.

public Task<T> Build<T, T1>(T1 data, params object[] args) where T : ICountryPage where T1 : ICountryObject
{
    var page = new CountryPage();
    return Task.FromResult(page);
}

CountryPage implements interface ICountryPage therefore I would expect this method to be able to return it.

However I get the error: Cannot convert expression type: System.Threading.Tasks.Task<CountryPage> to return type System.Threading.Tasks.Task<T>

I don't want to include the concrete type in the signature as this class implements an interface with this signature.

For clarity, my countryPage class looks like this

public class CountryPage: ICountryPage{}

And I am calling it thus

var response = service.Build<CountryPage, CountryPageObject>(data, args);

As this is a new development I can change any of the interfaces to make this work.


Solution

  • Because the compiler doesn't know how to convert Task<CountryPage> to Task<T>, if you can guarantee that T must be CountryPage, then you can force the conversion.

    public static Task<T> Build<T, T1>(T1 data, params object[] args) where T : ICountryPage where T1 : ICountryObject
    {
        T page = (T)(ICountryPage)(new CountryPage());
        return Task.FromResult(page);
    }