Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic object based on a Type variable [duplicate]

Tags:

c#

.net

generics

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

like image 953
Charlie Avatar asked Jun 05 '09 11:06

Charlie


People also ask

How do you indicate that a class has a generic type parameter?

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.

How do you initialize a generic class?

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.


1 Answers

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

like image 154
Marc Gravell Avatar answered Oct 08 '22 05:10

Marc Gravell