Bit of a puzzler, I have a generic class
public abstract class MyClass<T> : UserControl
{
}
and I have got a type like this
Type type = Type.GetType("Type From DB as String", true, true);
and I want to create and instance of MyClass using the type... But this doesn't work.
MyClass<type> control = (MyClass<type>)LoadControl("/UsercControl.ascx");
Any ideas????
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With