tags:

views:

465

answers:

1

I need to create a generic object based on a type that is stored in a database. How can I acheive this? The code below (which won't compile) explains what I mean:

string typeString = GetTypeFromDatabase(key);
Type objectType = Type.GetType(typeString);

//This won't work, but you get the idea!
MyObject<objectType> myobject = new MyObject<objectType>();

Is it possible to do this kind of thing?

Thanks

+15  A: 
Type type = typeof(MyObject<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);

Also - watch out; Type.GetType(string) only checks the executing assembly and a few system assemblies; it doesn't scan everything. If you use an assembly-qualified-name you should be fine - otherwise you may need to get the Assembly first, and use someAssembly.GetType(string).

Marc Gravell
Does the object that you're creating have to have a constructor that takes no arguments?
Charlie
@Charlie You've probably worked this out in the intervening year, but for completeness, no, you can use other constructors with [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx)`(Type, params Object[])`.
Mark Hurd