Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid variance: The type parameter must be invariantly valid but is covariant

What is wrong with this?

// does not compile
interface IRepository<out T>
{
    Task<T> Get(int id);
}

The compiler complains:

Invalid variance: The type parameter 'T' must be invariantly valid on ... 'T' is covariant.

However, when I remove the Task, the code compiles:

// compiles
interface IRepository<out T>
{
    T Get(int id);
}

Why would making an interface asynchronous cause it to not compile?

like image 425
JDawg Avatar asked Sep 30 '15 23:09

JDawg


1 Answers

As Asad mentioned above, Task<T> cannot be covariant because it is a class. The MSDN states:

Only interface types and delegate types can have variant type parameters.

If only there was a covariant ITask<T> interface.

After some googling, I found this suggested at visualstudio.uservoice.com. In the comments, Jeffrey Morse links to his implementation of ITask<T>.

Nice work Jeff!

like image 161
JDawg Avatar answered Oct 13 '22 00:10

JDawg