lokusking lokusking - 1 year ago 107
C# Question

Covariance and contravariance on Tasks

Given the followin snippet, i quite dont understand WHY what im going to achieve is not possible:


public interface IEntityRepository<out T> : IRepository<IEntity> {

void RequeryDataBase();

IEnumerable<T> Search(string pattern);

Task<IEnumerable<T>> SearchAsync(string pattern);

SearchContext Context { get; }

string BaseTableName { get; }

are just simple generic CRUD defined.

I get an Error on this line:
Task<IEnumerable<T>> SearchAsync(string pattern);


method return type must be output safe. invalid variance: the type parameter T must be invariantly valid on Task

Please help me understand, why i cant use
<out T>
with a

Answer Source

Task<T> is not covariant. Variance can only be applied to generic interfaces (and delegates, but that's not relevant here).

e.g. Task<IEnumerable<Dog>> cannot be assigned to Task<IEnumerable<Animal>>. Because of this, your interface cannot be marked as covariant either.

You might want to see this related question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download