Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

instantiate a List<T> where T is known at runtime using reflection

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
0
0
IT
Hallo,

I need to instantiate a generic list, but the type is going to be known only on runtime. Something like:

Type T = GetTheTypeUsingReflection();
List<T> myList = new List<T>();

But this code does not work: "the type 'T' could not be found"

Any suggestion?

Thanks
 
doing some research I found out the solution:

Type t = GetTheTypeUsingReflection();
IList newList = GetTypedList(t);

IList GetTypedList(Type itemType)
{
Type listType;
listType = typeof(List<>).MakeGenericType(itemType);
return Activator.CreateInstance(listType) as IList;
}
 
this seems counter intuitive. If you need an IList return an implementation of IList. Why create a a typed list through reflection? It would be much easier to return an ArrayList.

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top