Search code examples
c#.netreflectionsystem.reflection

Dynamically convert List<Object> to List<Customer>


I have a list, the type of the object will be found only at the runtime through reflection. But when I try to assign the list to the actual entity, it is throwing error as "object cannot be converted". Below is the code,

var obj = new List<Object>();
obj.Add(cust1);
obj.Add(Cust2);
Type newType = t.GetProperty("Customer").PropertyType// I will get type from property
var data= Convert.ChangeType(obj,newType); //This line throws error`

Solution

  • Your obj object ist not a Customer, it's a List of Customer. So you should get the type of it this way:

    var listType = typeof(List<>).MakeGenericType(t);
    

    But you couldn't convert your object to to this listType, you will get an Exception, that List doesn't implement IConvertible interface.

    Solution is: just to create new list and copy all data to it:

    object data = Activator.CreateInstance(listType);
    foreach (var o in obj)
    {
         listType.GetMethod("Add").Invoke(data, new []{o} );
    }