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
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.
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)
.
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