Sunday, September 21, 2008

Reflection in .Net is fairly commonplace and I've written it into dozens of applications.  Tonight I found a new case that I had not yet encountered: Creating a type that has a generic template parameter such as MyType<T>.

Without reflection, you would simply say: MyType<string> = new MyType<string>();.  But it is a bit more complicated creating the class dynamically at runtime, albeit very doable.

I found some helpful information online, but I really wish someone had just posted the following:

Activator.CreateInstance(Type.GetType(typeName).MakeGenericType(typeof(string)));

Let's deconstruct. 

- Activator.CreateInstance() creates an object from a type definition.  There are several ways of creating an object on the fly; this is only one of them.  You will need to add a reference to System.Reflection.

- Type.GetType(typeName) creates an object from a string definition of a type.  Again, many ways of doing this, but in this example, typeName = "namespace.namespace.className`1, fully-qualified assembly name", e.g. "NFC.Web.CustomType`1, NFC.Web".  Of course, your type name will be different, just make sure to use the fully-qualified class name and assembly name, seperated by a comma.

Note the red-highlighted code above; a generic class string must contain the `1 to indicate that it is a parameterized class.  If you had three generic parameters, you would mark it as `3 and so on.

- .MakeGenericType(params) - the crux of this solution.  Retrieves a type as a generic with the specified list of arguments.  In this example, we know the template argument and use typeof(x) to return its Type, but you could easily pass any (valid) type to this method.  In addition, as this method takes a params[], you can pass as many different template types into it.

 

- Tim Medora

 

posted on Sunday, September 21, 2008 8:40:45 PM (US Mountain Standard Time, UTC-07:00)  #    Comments [0]