Method call using dynamic with out parameter

I have Dictionary<string,K>

, where K is a type that is loaded via reflection, I cannot name K.

Unfortunately, I cannot figure out how I should use the method TryGetValue

. I tried a couple of different things and they all lead to exceptions. What should I do?

dynamic dict = GetDictThroughMagic();
dynamic d;
bool hasValue = dict.TryGetValue("name",out d);
bool hasValue = dict.TryGetValue("name",d);

      

I can write more detailed if(dict.Contains("name")) d=dict["name"]

But I would prefer to write a more concise TryGetValue approach.

Updated with the actual exception:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The
best overloaded method match for 'System.Collections.Generic.Dictionary<string,K>
.TryGetValue(string, out K)' has some invalid arguments
   at CallSite.Target(Closure , CallSite , Object , String , Object& )

      

+3


source to share


3 answers


You cannot do this, because in .Net, variables used as parameters ref

and out

must match the type exactly. And a variable dynamic

is actually a variable object

at runtime.

But you can get around this by toggling this parameter out

and which is the return value, although working with it will be less pleasant than usual TryGetValue()

:

static class DictionaryHelper
{
    public static TValue TryGetValue<TKey, TValue>(
        Dictionary<TKey, TValue> dict, TKey value, out bool found)
    {
        TValue result;
        found = dict.TryGetValue(value, out result);
        return result;
    }
}

      



Then you can call it like this:

dynamic dict = GetDictThroughMagic();
bool hasValue;
dynamic d = DictionaryHelper.TryGetValue(dict, "name", out hasValue);

      

+3


source


Why are you using dynamic

? Does this happen through interop? I would suggest using a generic abstraction that can be used here. Reflection doesn't mean dynamic, and this keyword is thrown in static language where it isn't needed. It was designed to intercept ...



More specific to your question: Here's what seems like a good answer . I don't believe the cast can work here because it can't cast type K.

+1


source


I recently ran into a similar error, but came up with a solution that provides access to the dictionary dynamics.

Try

dynamic dict = GetDictThroughMagic();
dynamic value = "wacka wacka"; // I renamed from 'd' and gave it a value
dynamic key = "name";

if (dict.ContainsKey(key))
{
    dict[key] = value;
} 

      

Hope this works for you!

0


source







All Articles