views:

2083

answers:

2

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.

+5  A: 
Type generic = typeof(List<>);    
Type specific = generic.MakeGenericType(typeof(int));    
ConstructorInfo ci = specific.GetConstructor(new Type[] { });    
object o = ci.Invoke(new object[] { });
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
A: 

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
@timbagas I formatted the code. When you posted it, it wasn't formatted and was hard to read. Claim down there are only two posts. If there where more I could see your point in getting angry.
Nathan W