Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Class & Type.GetType()

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????

like image 713
Andy Avatar asked Sep 24 '10 14:09

Andy


1 Answers

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.

like image 186
Jon Skeet Avatar answered Oct 04 '22 02:10

Jon Skeet