Func covariant assignment requires an explicit parameter

You can assign a method to a delegate with the corresponding args types:

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

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

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

But you cannot assign a method to a delegate with covariant args types:

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

Why not?

+4
source share
1 answer

The difference does not work with value types, since they must be JITed in different ways.

Your variant of lambda expression does not imply deviation; instead, it compiles into a lambda expression with an implicit conversion of the box from DateTimeto object.

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

Func<string, object> f = string.Intern;
+7
source

All Articles