I have a IEnumerable<Person> for example.
I want to be able to make it List<Person> at runtime
I have the below code but errors saying I can’t convert System Runtime type
Is there something I’m missing?
private static readonly MethodInfo enumerableToListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Public | BindingFlags.Static);
//genericType will be Person
var genericType = modelType.GetGenericArguments().First();
var genericToListMethod = enumerableToListMethod.MakeGenericMethod(new[] { genericType });
//modelType is IEnumerable<Person>
var ienumtype = genericToListMethod.Invoke(null, new object[] { modelType });
Activator.CreateInstance(ienumtype.GetType());
You’ve gotta pass in the IEnumerable to the invoke, NOT the type of the enumerable – also, calling invoke will return the List, not a Type.
put in code:
Based on your comments, I’m guessing you’re after something more like this:
Which you would call like:
Derp. Missed the call…