25

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.

svick
  • 236,525
  • 50
  • 385
  • 514
tim
  • 525
  • 2
  • 5
  • 9

2 Answers2

26
Type generic = typeof(List<>);    
Type specific = generic.MakeGenericType(typeof(int));    
ConstructorInfo ci = specific.GetConstructor(Type.EmptyTypes);    
object o = ci.Invoke(new object[] { });
Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
Tron
  • 1,397
  • 10
  • 11
  • 4
    This isnt a big deal or anything, but you can replace your empty type array being passed into GetConstructor with Type.EmptyTypes. Just a little cleaner, that's all. – Kilhoffer May 12 '09 at 14:09
8

You could use reflection for this:

Type t = typeof(Car);
System.Type genericType= generic.MakeGenericType(new System.Type[] { t});
Activator.CreateInstance(genericType, args);
Nathan W
  • 54,475
  • 27
  • 99
  • 146