I need to be able to access a property via reflection, and, knowing that this property is an IEnumerable, append an object to it.
Something like this:
Object o;
MemberInfo m;
Array arr; // Except use IEnumerable, may have to take account of value/ref types
arr = (Array)((PropertyInfo)m).GetValue(o, null); }
List<o.GetType()> newArr = new List<o.GetType()>(); /* fails */
newArr.AddRange(arr);
newArr.Add(o);
((PropertyInfo)m).SetValue(o, newArr.ToArray(), null);
Can you help me where I’m going wrong 🙂
Solution:
See accepted answer comments. Also (Get the actual type of a generic object parameter) is of help.
It sounds like you’re essentially asking how to make a
List<T>based on an unknown-at-compile-time type. For this you’ll have to use a bit more reflection magic:That would create a
List<T>out of a runtime type.But really, your code would be much simpler if you simply use ArrayList: