Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# compiler error 'Parameter must be input safe. Invalid variance. The type parameter 'T' must be invariantly valid on Expression<TDelegate> '

I want to use my interface co-variantly (Interface must be co-variant) but the Compiler give me error c# compiler error:- 'Parameter must be input safe. Invalid variance. The type parameter 'T' must be invariantly valid on 'Expression' This is my code:

interface IRepository<out T> where T : BaseEntity
{
    IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
    T FindById(Guid id);
}
like image 972
yo2011 Avatar asked Jun 17 '14 23:06

yo2011


1 Answers

You declared T as covariant (using the out keyword) but you cannot take covariant parameters:

(MSDN)

In general, a covariant type parameter can be used as the return type of a delegate, and contravariant type parameters can be used as parameter types. For an interface, covariant type parameters can be used as the return types of the interface's methods, and contravariant type parameters can be used as the parameter types of the interface's methods.

Func<T, bool> takes a Targument and returns a bool breaking this rule. You could mark it as contravariant, but you return a T in the next function.

You could try and beat it by taking two type parameters (one covariant and one contravariant), something like:

interface IRepository<out T, in U> where T : BaseEntity
                                   where U : BaseEntity
{
    IEnumerable<T> Find(Expression<Func<U, bool>> predicate);
    T FindById(Guid id);
}

I seriously doubt its what you are looking for, and I'm not sure it would even compile/work, but it might help.

like image 101
BradleyDotNET Avatar answered Sep 19 '22 16:09

BradleyDotNET