Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariant assignment to Func requires explicit parameter

You can assign a method to a delegate with matching type args:

Func<string, DateTime> f = DateTime.Parse;

You can assign a lambda to a delegate with covariant type args:

Func<string, object> f = s => DateTime.Parse(s);

But you can't assign a method to a delegate with covariant type args:

Func<string, object> f = DateTime.Parse; //ERROR: has the wrong return type

Why not?

like image 359
Daniel Avatar asked Mar 22 '23 00:03

Daniel


1 Answers

Variance does not work with value types, since they need to be JITed differently.

Your lambda expression variant does not involve variance; instead, it compiles to a lambda expression with an implicit boxing conversion from DateTime to object.

If you use a method that returns a reference type, it work fine:

Func<string, object> f = string.Intern;
like image 66
SLaks Avatar answered Apr 02 '23 22:04

SLaks