Reputation: 549
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.
Upvotes: 3
Views: 3602
Reputation: 3311
According to a first exception you are trying to cast Eclipsys.Enterprise.Entities.Registration.VisitLite
to List<>
. I think that's your problem.
Try this:
businessObject = //your collection;
//there might be two Add methods. Make sure you get the one which has one parameter.
MethodInfo addMethod = businessObject.GetType().GetMethods()
.Where(m => m.Name == "Add" && m.GetParameters().Count() == 1).FirstOrDefault();
foreach(object obj in businessObject as IEnumerable)
{
addMethod.Invoke(businessObject, new object[] { obj });
}
Upvotes: 5