38

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

0

1 Answer 1

74
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).

Sign up to request clarification or add additional context in comments.

2 Comments

Does the object that you're creating have to have a constructor that takes no arguments?
@Charlie You've probably worked this out in the intervening year, but for completeness, no, you can use other constructors with Activator.CreateInstance(Type, params Object[]).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.