Dynamically convert List<Object> to List<Customer>

739 views Asked by At

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`
1

There are 1 answers

0
Maksim Simkin On BEST ANSWER

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