Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast IEnumerable<T> to runtime type

Tags:

c#

How can achieve something similar to listOfBaseItems.Cast<Child>() using a type defined in runtime? e.g.

var t = typeof(Child); // the type would be a method argument in my case
var desiredType = typeof(List<>).MakeGenericType(t);
var castedList = Convert.ChangeType(listOfBaseItems, desiredType);

I get an exception that the items doesn't implement IConvertible. What am I missing?

like image 636
filur Avatar asked Apr 05 '26 16:04

filur


1 Answers

Assuming that the cast is legal (e.g. listOfBaseItems actually contains child items), then you can invoke Cast (which is a generic extension method in the Enumerable class) at runtime like this:

var result = 
    typeof(Enumerable)
        .GetMethod("Cast")
        .MakeGenericMethod(t)
        .Invoke(null, new object[] {listOfBaseItems});
like image 109
Yacoub Massad Avatar answered Apr 08 '26 05:04

Yacoub Massad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!