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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With