Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying generic collection type param at runtime [duplicate]

Tags:

I have:

class Car {..} class Other{   List<T> GetAll(){..} } 

I want to do:

Type t = typeof(Car); List<t> Cars = GetAll<t>(); 

How can I do this?

I want to return a generic collection from the database of a type that I discover at runtime using reflection.

like image 861
tim Avatar asked Feb 05 '09 00:02

tim


2 Answers

Type generic = typeof(List<>);     Type specific = generic.MakeGenericType(typeof(int));     ConstructorInfo ci = specific.GetConstructor(Type.EmptyTypes);     object o = ci.Invoke(new object[] { }); 
like image 89
Tron Avatar answered Oct 05 '22 04:10

Tron


You could use reflection for this:

Type t = typeof(Car); System.Type genericType= generic.MakeGenericType(new System.Type[] { t}); Activator.CreateInstance(genericType, args); 
like image 35
Nathan W Avatar answered Oct 05 '22 04:10

Nathan W