2008-01-31

Dynamic instantiation of generic types

If at first you don't succeed...Change the rules.

Once I had managed to create the implementation of IList[T] (see last post), I was faced with the problem of instantiating it dynamically. All I had was the type and a reference to the type that I wanted to substitute for T. The argument to the generic type was not fixed statically.

I tried to get System.Type.GetType(string s) to return the type:

System.Type.GetType(
'MyNameSpace.MyGenericType`1[MyOtherNameSpace.MyOtherType]');


but it simply didn't want to return my type. I finally settled for this:


Type arg = (* expression that resulted in a type reference *)
object temp = new MyGenericType[object]();
Type t = temp.GetType.
GetGenericTypeDefinition.MakeGenericType(new Type[]{arg});
object newObj = Activator.CreateInstance(
t,
new object[]{ (* constructor parameters *)} );

Anyone know a way around the Activator class to improve performance?

No comments: