Search code examples
c#genericsreflectioncollectionscasting

C# How to set PropertyInfo value when its type is a List<T> and I have a List<object>


I have an object with a generic List property where T is a primitive value, string, or enum. The generic argument of this list will never be a reference type (except for string). Now, I have another List who's argument type is object. Is there a way to set that property's value with my object list? As in:

List<object> myObjectList = new List<object>();
myObjectList.Add(5);

property.SetValue(myObject, myObjectList, null);

When I know that the property's real type is:

List<int>

The only solution I can see to it is making a hard coded switch that uses the generic argument's type of the list property and creates a type safe list. But it would be best if there were a general case solution. Thanks!


Solution

  • You should create an instance of the property's real type, if you know it really will be a List<T> for some T (rather than an interface, for example). You can then cast to IList and add the values to that, without knowing the actual type.

    object instance = Activator.CreateInstance(property.PropertyType);
    // List<T> implements the non-generic IList interface
    IList list = (IList) instance;
    list.Add(...); // Whatever you need to add
    
    property.SetValue(myObject, list, null);