Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use a lambda expression as an argument to a dynamically dispatched

I have a concurrent Dictionary in C#:

private static ConcurrentDictionary<string, dynamic> cache =
        new ConcurrentDictionary<string, dynamic>();

I'm trying to add or update a dynamic value to the dictionary

public void SetCache(string key, dynamic value)
{
       cache.AddOrUpdate(key, value, (k, v) => value);
}

but I get the following error. What is the problem with the code? Example here.

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.

like image 704
Tal Avissar Avatar asked May 10 '17 10:05

Tal Avissar


2 Answers

The error message is pretty clear I think.

An anonymous lambda can represent a delegate (and there can be many matching delegate types) or an expression tree. It does not have a type by itself until assigned to a variable of specific type or, used in a context where a specific type is expected. When regular (non-dynamic) types are used the compiler can usually deduce target type (such as Func<string, string>). When dynamic types are involved though - compiler cannot do that, because all resolutions are now performed at runtime, not at compile time. So compiler will not assign type Func<string, dynamic, dynamic> to your lambda and you should do it yourself (as compiler suggests):

cache.AddOrUpdate(key, value, (Func<string, dynamic, dynamic>) ((k, v) => value));

Example here.

like image 87
Evk Avatar answered Nov 06 '22 04:11

Evk


A dynamic just bypasses static type checking. However you are trying to use it as a code pointer, and as the error says, you need to cast it to a delegate or expression tree. The static type checking is not bypassed in this circumstance.

like image 42
PhillipH Avatar answered Nov 06 '22 03:11

PhillipH