Question

I am trying to edit the properties of an object's properties while looping through said object's properties. Ok, that was hard to get out of my head! Hopefully a code example will help here!

MyObject object = new MyObject();
foreach (PropertyInfo propInfo in typeof(MyObject).GetProperties())
{
    if (propInfo.PropertyType.ToString().Contains("System"))
    {
        continue;
    }
    foreach (PropertyInfo subPropInfo in propInfo.PropertyType.GetProperties())
    {
         if (subPropInfo.PropertyType.ToString().Contains("System"))
         {
              continue;
         }
         else
         {
            // Set the value here
         }
    }
}

I can use SetValue(object, "value") in the first loop of object but I can't work out how to use it in the nested loop. Is there a way to do this or am I completely going about this the wrong way?

Was it helpful?

Solution

To get the value of the sub property you get the value of the outer property and use that as the "object" for the sub property's Info object:

var subPropertyValue = subPropInfo.GetValue(propInfo.GetValue(obj, null), null);

To set it; same idea:

subPropInfo.SetValue(propInfo.GetValue(obj, null), someValue);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top