Using reflection read properties of an object containing array of another object

Sri Reddy picture Sri Reddy · Feb 2, 2011 · Viewed 29.6k times · Source

How can I read the properties of an object that contains an element of array type using reflection in c#. If I have a method called GetMyProperties and I determine that the object is a custom type then how can I read the properties of an array and the values within. IsCustomType is method to determine if the type is custom type or not.

public void GetMyProperties(object obj) 
{ 
    foreach (PropertyInfo pinfo in obj.GetType().GetProperties()) 
    { 
        if (!Helper.IsCustomType(pinfo.PropertyType)) 
        { 
            string s = pinfo.GetValue(obj, null).ToString(); 
            propArray.Add(s); 
        } 
        else 
        { 
            object o = pinfo.GetValue(obj, null); 
            GetMyProperties(o); 
        } 
    } 
}

The scenario is, I have an object of ArrayClass and ArrayClass has two properties:

-string Id
-DeptArray[] depts

DeptArray is another class with 2 properties:

-string code 
-string value

So, this methods gets an object of ArrayClass. I want to read all the properties to top-to-bottom and store name/value pair in a dictionary/list item. I am able to do it for value, custom, enum type. I got stuck with array of objects. Not sure how to do it.

Answer

EvgK picture EvgK · Feb 2, 2011

Try this code:

public static void GetMyProperties(object obj)
{
  foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    var getMethod = pinfo.GetGetMethod();
    if (getMethod.ReturnType.IsArray)
    {
      var arrayObject = getMethod.Invoke(obj, null);
      foreach (object element in (Array) arrayObject)
      {
        foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties())
        {
          Console.WriteLine(arrayObjPinfo.Name + ":" + arrayObjPinfo.GetGetMethod().Invoke(element, null).ToString());
        }
      }
    }
  }
}

I've tested this code and it resolves arrays through reflection correctly.