RKN
RKN

Reputation: 962

Using System.Threading.Task<T> as covariant type parameter to an generic interface

Any specific reason that Task cannot be used as covariant type parameter in generic interface as below code?

public interface Results<in TInput, out TOutput>
{
    Task<TOutput> ResultAsync(TInput query);
}

If I remove Task or out it is allowed,

public interface Results1<in TInput, out TOutput>
{
    TOutput ResultAsync(TInput query);
}
OR 
public interface Results1<in TInput, TOutput>
{
    Task<TOutput> ResultAsync(TInput query);
}

Is there any workaround to have Task as covariant type parameter?

Upvotes: -1

Views: 100

Answers (1)

Jonathan Apps
Jonathan Apps

Reputation: 49

The reason for the restriction is related to variance. Task is a class, and classes in C# are ALWAYS invariant. The compiler expects that your Task can be substituted with some type, but the substitution is not permitted since Task is invariant - hence the issue.

There is not a workaround to having Task as a covariant type parameter since it is invariant by definition.

Upvotes: 1

Related Questions