C# – Get dictionary key-value pairs without knowing its type

c++dictionaryreflection

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?

Best Solution

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();