Monday, November 1, 2010

Dynamic List

I needed to create a method that would take any type, and return a List of that type. The catch was I didn't know what type T would be. How to get that done?

Like this:
1:  private object CreateList(Type type){
  
2:   System.Collections.IList lst = (System.Collections.IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(type)));
  
3:  return lst;
  
4:  }  

Your calling code will need to cast the return correctly, but that one line will get you your dynamic typed list.

No comments:

Post a Comment