Covariance with a common type and expression

I try to use covariance in my Program, but when I use Expression<Func<T>> in my method as a parameter, I get the following error

The parameter must be safe for input. Invalid variance.
Type T parameter must be invalid on Expression <TDelegate>

Can an expression be used as a parameter in a method along with covariance?

Example below

 class Program { static void Main(string[] args) { var temp = new Temp<People>(); TestMethod(temp); } public static void TestMethod(ITemp<Organism> param) { } } class Temp<T> : ITemp<T> where T : Organism { public void Print() {} public void SecondPrint(Expression<Func<T>> parameter) {} } class People : Organism {} class Animal : Organism {} class Organism {} interface ITemp<out T> where T : Organism { void SecondPrint(Expression<Func<T>> parameter); } 
+4
source share
1 answer

See Eric Lippert answer :

"Output" means that "T is used only in output positions." You use it in the entry position

(even if it is a Func delegate return type). If the compiler allowed this, you could write (in your example):

 static void Main(string[] args) { var temp = new Temp<People>(); TestMethod(temp); } public static void TestMethod(ITemp<Organism> param) { param.SecondPrint(() => new Animal()); } 

Call SecondPrint on Temp<People> , but passing a lambda that returns Animal .

I would remove the variance annotation on T :

 interface ITemp<T> where T : Organism { void SecondPrint(Expression<Func<T>> parameter); } 

and make TestMethod parametric in T :

 public static void TestMethod<T>(ITemp<T> param) where T : Organism { } 
0
source

Source: https://habr.com/ru/post/1502051/


All Articles