May 2006 Entries

How to dynamically create a generic type

Today, I ran up against a situation where I needed to create a generic type dymnamically, e.g. to specify what type the object was built around on the fly. I spent a while trying several different methods (Reflection.Emit, Lightweight Code Generation (LCG), etc.), but it turns out I was dramatically over-engineering the problem. In .NET 2.0, there is a new Type.MakeGenericType method that returns a new type that accepts a paramarray of types and returns a generic type built from those parameters. Here is the basic usage, using the generic List<T> class for an example: Type genericParameterType = typeof(string); Type genericType = typeof(List<>).MakeGenericType(genericParameterType); ConstructorInfo...

posted @ Tuesday, May 02, 2006 11:18 AM | Feedback (0)