Hans
Hans

Reputation: 565

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!

Upvotes: 4

Views: 12845

Answers (2)

Random Dev
Random Dev

Reputation: 52290

Yes there is - you can do something like this:

property.SetValue(myObject, myObjectList.Cast<int>().ToList(), null);

this is using Enumerable.Cast so note that this will throw an runtime exception if there are values not of type int in your list.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502076

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);

Upvotes: 10

Related Questions