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?
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();
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With