Tried to something like this in our code but it fails:
Func<Employee, Employee> _myFunc;
void Main()
{
Func<Employee, Employee> test1 = _myFunc;//Ok
Func<Employee, Person> test2 = _myFunc;//Ok
Func<Person, Employee> test3 = _myFunc;//Fails
Func<Person, Person> test4 = _myFunc;//Fails
}
public class Person { }
public class Employee : Person { }
The last two cases give this error:
Cannot implicitly convert type
System.Func<Employee, Employee>
toSystem.Func<Person, Employee>
. An explicit conversion exists (are you missing a cast?)
Any idea why?
Func<>
) is covariant, while the input parameters (all the other generic parameters ofFunc<>
) are contravariant. – FuegianGiraffe M(Animal a)
anddelegate Animal D(Tiger t)
thenD d = M;
is legal in C#, even though D is not even generic. – Glim