So I'm fairly new to Reflection but recently have found it extremely useful. But I've hit a road block. Essentially right now I'm looping the properties of a class which I've obtained with reflection and doing something depending on what kind of data the property contains (int, string, enum, etc) and in doing so modify the data within the property. This was pretty straight forward using the propertyInfo.SetValue() method which has worked for all the other cases I need to handle. However, for a list I can't just set value because I'm not trying to set the value of the list I want to be able to add and remove items from the list as well as change the values of items within the list. And this all as to be dynamic. Below is an example of what I'm trying to do:
MyAbstractClass classInstance; //this may contain one of many classes inheriting from 'MyAbstractClass'
PropertyInfo[] properties = classInstance.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
//this would be proceeded by other type case checks, this is the case that it's a list
else if (prop.PropertyType.GetInterface(typeof(List<>).FullName) != null)
{
Type contentType = prop.PropertyType.GetGenericArguments()[0]; //get the type of data held in list
//BEGIN EXAMPLES OF WHAT I'D LIKE TO DO
prop.GetValue(classInstance).Add(Activator.CreateInstance(contentType));
prop.GetValue(classInstance).RemoveAt(3);
prop.GetValue(classInstance)[1] = someDataThatIKnowIsCorrectType;
}
}
I have so much else figured out and learned so much just through internet research but I've been unable to find this last piece of the puzzle I'm trying to put together, or potentially unable to recognize a solution to my problem if I did see come across it.
Thanks for the help!
You can cast the value to
IList
and useAdd(object value)
method:Also personally I would implement property type check like this: