How can I instantiate a List<Foo>
or List<Bar>
at runtime by providing the System.Type value to a constructor? This question has to be answered many times but I can't find it.
Ultimately, I want to make an extension method like so:
public static IEnumerable<T> CreateEnumerable<T>(this System.Collections.IEnumerable list, Type type){
var stuff = something;
// magic happens to stuff where stuff becomes an IEnumerable<T> and T is of type 'type'
return stuff as IEnumerable<T>;
}
You can specify the parameter of List<>
at runtime using reflection and the MakeGenericType
method.
var typeParam = typeof(Foo);
var listType = typeof(List<>).MakeGenericType(typeParam);
And then instantiate it using the Activator
class
var list = Activator.CreateInstance(listType);
However, if all you're trying to do is turn an IEnumerable
into an IEnumerable<T>
, Linq already has methods (Cast
and OfType
) to do this:
IEnumerable untypedList = ...
var foos = untypedList.Cast<Foo>(); // May throw InvalidCastException
var bars = untypedList.OfType<Bar>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With