C# Reflection and Getting Properties

Still not 100% sure of what you want, but this quick bit of code (untested) might get you on the right track (or at least help clarify what you want).

void ReportValue(String propName, Object propValue);

void ReadList<T>(List<T> list)
{
  var props = typeof(T).GetProperties();
  foreach(T item in list)
  {
    foreach(var prop in props)
    {
      ReportValue(prop.Name, prop.GetValue(item));
    }
  }
}

c# should be able to work out that ‘PeopleList’ inherits from ‘List’ and handle that fine, but if you need to have ‘PeopleList’ as the generic type, then this should work:

void ReadList<T>(T list) where T : System.Collections.IList
{
  foreach (Object item in list)
  {
    var props = item.GetType().GetProperties();
    foreach (var prop in props)
    {
      ReportValue(prop.Name, prop.GetValue(item, null));
    }
  }
}

Note that this will actually process properties in derived types within the list as well.

Leave a Comment