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?
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});
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