Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic generics at runtime using Reflection

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?

like image 784
MPhlegmatic Avatar asked Feb 27 '11 10:02

MPhlegmatic


2 Answers

The C# compiler emits System.Object as the type for "dynamic". "dynamic" is a language-specific construct and has no corresponding type in the Common Language Infrastructure. As such, you won't be able to use reflection to create a "dynamic" nor use "dynamic" as a generic type parameter.

A Dictionary<dynamic, dynamic> is really a Dictionary<object, object>. What "dynamic" means to the compiler is simply late-bind any member accesses for the object using reflection (the implementation of which lies in the Microsoft.CSharp assembly in case you're curious).

On a side note, the compiler will also emit an attribute, DynamicAttribute, on fields, parameters, etc. that are "dynamic"; that allows people consuming the assembly's metadata to distinguish between a System.Object and a "dynamic". This is how IntelliSense shows a method's parameter as dynamic from an assembly reference, for example.

like image 180
Peter Huene Avatar answered Sep 29 '22 09:09

Peter Huene


Dictionary<MyType, Object>

Activator.CreateInstance(typeof (Dictionary<dynamic, dynamic>));

This actually creates a Dictionary<Object, Object>

The only use I can see from using dynamic instead of object is during code typing you can use dic["some"].MyDynProperty.... but if you create you object with Activator it will return Object so no use in code typing...

like image 34
Alex Burtsev Avatar answered Sep 29 '22 10:09

Alex Burtsev