I am trying to get the values from objects inside a list which is part of a main object.
I have the main object which contains various properties which can be collec
See if something like this helps you in the right direction: I got the same error a while back and this code snipped solved my issue.
PropertyInfo[] properties = MyClass.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.Name == "MyProperty")
{
object value = results.GetType().GetProperty(property.Name).GetValue(MyClass, null);
if (value != null)
{
//assign the value
}
}
}
To Get/Set using reflection you need an instance. To loop through the items in the list try this:
PropertyInfo piTheList = MyObject.GetType().GetProperty("TheList"); //Gets the properties
IList oTheList = piTheList.GetValue(MyObject, null) as IList;
//Now that I have the list object I extract the inner class and get the value of the property I want
PropertyInfo piTheValue = piTheList.PropertyType.GetGenericArguments()[0].GetProperty("TheValue");
foreach (var listItem in oTheList)
{
object theValue = piTheValue.GetValue(listItem, null);
piTheValue.SetValue(listItem,"new",null); // <-- set to an appropriate value
}