I'm trying to use reflection to add an unknown object to an unknown collection type, and I'm getting an exception when I actually perform the "Add". I wonder if anyone can point out what I'm doing wrong or an alternative?
My basic approach is to iterate through an IEnumerable which was retrieved through reflection, and then adding new items to a secondary collection I can use later as the replacement collection (containing some updated values):
IEnumerable businessObjectCollection = businessObject as IEnumerable;
Type customList = typeof(List<>)
.MakeGenericType(businessObjectCollection.GetType());
var newCollection = (System.Collections.IList)
Activator.CreateInstance(customList);
foreach (EntityBase entity in businessObjectCollection)
{
// This is the area where the code is causing an exception
newCollection.GetType().GetMethod("Add")
.Invoke(newCollection, new object[] { entity });
}
The exception is:
Object of type 'Eclipsys.Enterprise.Entities.Registration.VisitLite' cannot be converted to type 'System.Collections.Generic.List`1[Eclipsys.Enterprise.Entities.Registration.VisitLite]'.
If I use this line of code for the Add()
instead, I get a different exception:
newCollection.Add(entity);
The exception is:
The value "" is not of type "System.Collections.Generic.List`1[Eclipsys.Enterprise.Entities.Registration.VisitLite]" and cannot be used in this generic collection.