Creating dynamic generics at runtime using Reflection

Posted by MPhlegmatic on Stack Overflow See other posts from Stack Overflow or by MPhlegmatic
Published on 2011-02-27T10:24:52Z Indexed on 2011/02/27 15:24 UTC
Read the original article Hit count: 227

Filed under:
|
|
|

I'm trying to convert a Dictionary< dynamic, dynamic > to a statically-typed one by examining the types of the keys and values and creating a new Dictionary of the appropriate types using Reflection. If I know the key and value types, I can do the following:

Type dictType = typeof(Dictionary<,>);

        newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType }));

However, I may need to create, for example, a Dictionary< MyKeyType, dynamic > if the values are not all of the same type, and I can't figure out how to specify the dynamic type, since

typeof(dynamic)

isn't viable.

How would I go about doing this, and/or is there a simpler way to accomplish what I'm trying to do?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics