1

In .NET 6, I have an interface and a type:

internal interface IProvider
{
}

public class TProvider : IProvider
{
}

I want to use a covariant T in another interface like this:

internal interface IFactory<out T>
{
    Task<T> Create();
}

But on the line Task<T> Create(), I am getting an error:

The type parameter 'T' must be invariantly valid on 'IFactory.Create()'. 'T' is covariant

If I change the method call to a synchronous version -- T Create() -- it compiles.

Is there a way to keep T as covariant and return Task<T> as part of an asynchronous method signature?

user1044169
  • 2,686
  • 6
  • 35
  • 64
  • Natively this isn't possible, it would be good to know more about your use case on what you need this for. There may be alternatives. There's also a discussion here regarding this state https://github.com/dotnet/roslyn/issues/2981 – itsdaniel0 Mar 02 '23 at 07:34
  • The short answer is "no" (at least currently) – Marc Gravell Mar 02 '23 at 07:34
  • Related: [Why isn't Task covariant?](https://stackoverflow.com/questions/30996986/why-is-taskt-not-co-variant#:~:text=The%20justification%20is%20that%20the,single%20place%20in%20their%20code). – John Wu Mar 02 '23 at 08:06

1 Answers1

-1

Change this:

internal interface IFactory<out T>
{
    Task<T> Create();
}

To :

internal interface IFactory<T>
{
    Task<T> Create();
}
Siba Daki
  • 9
  • 2