I have a list of objects created using reflection, they are all the same type, however the type is unknown at compile time.
I'm trying to figure out the best way of assigning this list (also using reflection) to an object property which could be any IEnumerable.
List<object>
ArrayList
Custom : List<object>
The only approach I have is to assume the property is an ICollection then loop through the IEnumerable and add each item. (See below, where list
is the IEnumerable source, key
is the string name of the object property and result
is the object itself)
foreach (object item in list) {
PropertyInfo prop = result.GetType().GetProperty(key);
var collection = prop.GetValue(result, null);
Type collectionType = collection.GetType();
MethodInfo add = collectionType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
add.Invoke(collection, new object[] { item });
}
Since you say the data is homogeous, I would suggest typing it as closely as you can; so assuming
list
is non-empty,list[0].GetType()
will tell you theType
of all the data. At this point, you could do:or you could use an array:
Either of which will give you a well typed list, which tends to work much better for most purposes (data-binding, serialization, or just reflection).
If
list
is not actually a list, but is justIEnumerable
, then you can basically still do the same thing, but simply defer the creation until the first item:There are a couple of ways that you can add items to an existing collection of not known type:
Check for the
IList
interface or check of anAdd
method as a fallback;I would probably go with Marc's way since it's more type safe.