14476

Calling a method using dynamic with an out parameter

Question:

I have a Dictionary<string,K> where K is a type that is loaded through reflection, I can't name K.

Unfortunately, I can't figure out how I'm supposed to use the TryGetValue method. I tried a couple of different things and they all lead to exceptions. What am I suppose to do?

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

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

But I'd prefer if I could write the more concise TryGetValue approach.

Updated to include 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& )

Answer1:

You can't do that, because in .Net, variables used as ref and out parameters must match the type exactly. And a dynamic variable is actually an object variable at runtime.

But you could work around that by switching which parameter is out and which is the return value, although working with that would be less nice than normal 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; } }

You could then call it like this:

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

Answer2:

Why are you using a dynamic? Is this coming via an interop? I would suggest using a common abstraction that can be used here. Reflection does not mean dynamic, and this keyword is being thrown around in a static language in places that it is not needed. It was designed for interops...

More specific to your question: <a href="https://stackoverflow.com/questions/3929444/dynamic-type-in-method-parameter" rel="nofollow">Here is what seems like a good answer</a>. I do not believe that the cast can work here because it cannot cast up to type K.

Answer3:

I recently came across the similar error but came to a solution making all access to the dictionary dynamic.

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 out for you!

Recommend

  • Self referencing generic type constraint and XAML in UWP application
  • extending c# syntax with roslyn
  • An alternative for “CSharpCodeProvider.Parse”
  • Getting 'An existing connection was forcibly closed by the remote host.' from Azure
  • When I minimize my application all of my drawings disappears
  • C# Uncaught exception in unit test
  • Case insensitive property mapping
  • Building with .NET Native tool chain causes error with missing property in dynamic object
  • C# Generic Operators
  • How can i copy from a .NET Bitmap all pixels to av_image frame data?
  • Travis unable to find csharp solution
  • Downloading image via libcurl
  • Compilation Error - The compiler failed with error code 1 - asp.net error after publishing
  • Why are “Extracted Interfaces” Internal rather than Public?
  • Move Html.DropDownListFor into EditorTemplate
  • LINQ Let operator with lambda syntax
  • Websocket issue with IIS 8 Express on Windows 7
  • How can I extract Git commit hash from VS/msbuild?
  • Calling a method using dynamic with an out parameter
  • Receiving a broadcast message in C# [duplicate]
  • C#: Find out result type of arithmetic operations in code (e.g. int + double = double)
  • Generate setup.exe for ClickOnce deployment from command line using MSBuild
  • Embed Barcode in C# PDF Library
  • Why can't I use constants in [SuppressMessage(…)] together with StyleCop?
  • System.Data.SQLite BadImageFormatException with NHibernate, works finewhen standalone
  • Why has Haskell troubles resolving “overloaded” operators?
  • Antialias on clipPath on layout
  • How do I correctly parse a URI query string into a name-value collection in C#?
  • Trying to string.Join an IList
  • Get specific string
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • why overloaded new operator is calling constructor even I am using malloc inside overloading functio
  • Extracting HTML between tags
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Validaiting emails with Net.Mail MailAddress
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?