Let's say I have retrieved a System.Type
object using reflection and want to use that type to convert a List<Object>
into another List of that type.
If I try:
Type type = GetTypeUsingReflection();
var myNewList = listObject.ConvertAll(x => Convert.ChangeType(x, type));
I get an exception since the object does not implement the IConvertible
interface. Is there a way around this or another way to approach this problem?
There's no way for the type system to go from a type variable storing type T to a generic parameter of type T.
Technically you can create a generic list of the correct type (using reflection), but the type information is not available at compile time.
But why on Earth would you need it?
Casting is of little use when the type is not known at design-time. Once you have your new list of objects cast to your new type, how are you going to make use of the new type? You can't call a method that the type exposes (without using more reflection)
Your proposed solution wouldn't actually work anyway - it'll just create another
List<Object>
, because the return type ofChangeType
isObject
.Assuming you just want casting, you could do something like this: