Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dictionary key-value pairs without knowing its type

I have an object instance for which

instance.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)

is true. My question is, how can I extract the key-value pairs from this object without actually knowing their generic types? I would like to get something like KeyValuePair<object, object>[]. Note that I also know the generic types the dictionary uses at runtime (but not compile-time). I assume some kind of reflection is required?

FOLLOW-UP: Is there a general mechanism to convert an object to SomeClass<> (if I know that is the correct type, of course) and thus use it, given that the implementation of the class is not affected by the type of generic arguments?

like image 502
nickolayratchev Avatar asked May 12 '13 02:05

nickolayratchev


2 Answers

I would do what Jeremy Todd said except maybe a little bit shorter:

    foreach(var item in (dynamic)instance)
    {
       object key = item.Key;
       object val = item.Value;
    }

And as a side note (not sure if helpful), you can get the types of the arguments like this:

Type[] genericArguments = instance.GetType().GetGenericArguments();
like image 169
Dimitar Dimitrov Avatar answered Sep 21 '22 13:09

Dimitar Dimitrov


For a quick solution, you could just use dynamic:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();

myDictionary.Add("First", 1);
myDictionary.Add("Second", 2);
myDictionary.Add("Third", 3);

dynamic dynamicDictionary = myDictionary;

foreach (var entry in dynamicDictionary)
{
  object key = entry.Key;
  object val = entry.Value;
  ...whatever...
}
like image 38
Jeremy Todd Avatar answered Sep 21 '22 13:09

Jeremy Todd