Bit of a puzzler, I have a generic class
public abstract class MyClass : UserControl
{
}
and I have got a type like this
<
Generics in reflection are a bit more complex than this. What you're looking for are the GetGenericTypeDefinition() and MakeGenericType() methods. Take your generic type (you can get it by calling GetType() on an instance, or using typeof(MyClass<Object>
)), and call GetGenericTypeDefinition() to get the basic, open generic type (MyClass<T>
). Then, on that type, call MakeGenericType() and pass it an array with one element; the type you want to use to close the generic. That will get you a generic type closed with your dynamically discovered type (MyClass<MyType>
), which you can pass to Activator.CreateInstance().
You must construct the class via reflection.
See http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx for more details.
You create new objects using reflection:
type.GetConstructor(new Type[]{}).Invoke(new object[]{});
Something like this:
Type typeArgument = Type.GetType("Type From DB as String", true, true);
Type template = typeof(MyClass<>);
Type genericType = template.MakeGenericType(typeArgument);
object instance = Activator.CreateInstance(genericType);
Now you won't be able to use that as a MyClass<T>
in terms of calling methods on it, because you don't know the T
... but you could define a non-generic base class or interface with some methods in which don't require T
, and cast to that. Or you could call the methods on it via reflection.