Cannot use a lambda expression as an argument to a dynamically dispatched
c#, concurrency, lambda
Solution
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.
Problem
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.