Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a dictionary as a parameter when I don't care about a dictionary's types?

Similar to this question:

Best way to convert Dictionary<string, string> into single aggregate String representation?

But I want to ignore the types in the Dictionary, since I plan on calling the ToString() method of each key and value.

I think it should not be a problem, but I cannot figure out how to pass in an untyped dictionary, short of just casting it as Object... any ideas?

[EDIT] Add working code snippet: This works - thanks twoflower

public string DumpDictionary<TKey, TElement>(IDictionary<TKey, TElement> dictionary)
{
      StringBuilder sb = new StringBuilder();
      foreach (var v in dictionary)
      {
           sb.AppendLine(v.Key.ToString() + ":" + v.Value.ToString());
      }
      return sb.ToString();
 }
like image 658
Aerik Avatar asked Mar 08 '12 22:03

Aerik


1 Answers

What about just

void DumpDictionary<TKey, TElement>(IDictionary<TKey, TElement> dictionary)
{
   ...
}

You can then call this without the type arguments since they will be inferred (in most cases):

var dictionary = new Dictionary<long, MyClass>();
...
DumpDictionary(dictionary); 
like image 83
twoflower Avatar answered Oct 15 '22 05:10

twoflower