Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a generic collection using a Type argument

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>;
}
like image 552
Jeremy Holovacs Avatar asked Dec 26 '22 08:12

Jeremy Holovacs


1 Answers

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>();
like image 174
p.s.w.g Avatar answered Jan 11 '23 03:01

p.s.w.g