Monday, March 12, 2007

T From Type Generics #2

Generics are fun. but from the first day I started playing with it, I was intrigued by one main question: how to really make it dynamic.

The hole problem lays in T - how the hell, do I create an instance of a generic type???

To be more clear, I'll give an example:


Lets say I have the following class:


public class GenericChild
{ /* Some Code Here */ }


Now, I want to be able to create GenericChild objects dynamically - at runtime, like the following:


public static void Main()
{
  object child = CreateChild(Type.GetType("System.Collections.ArrayList");


How will you implement the "CreateChild" method?


Type.MakeGenericType
Thanks to Oliver Sturm, I found out, that the Type object has been quite extended,
Take a look at the answer:


public static object CreateChild(Type t)
{
  Type origType = typeof(GenericChild<>);
  Type genType = origType.MakeGenericType(childType);
  return genType.Assembly.CreateInstance(genType.FullName);
}


Ah, the wonders of Generics ;)

No comments: