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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With