Iterating Through a Collection Using Reflection

I ran into an issue today using reflection.  I was getting properties on a object using the following code:

   1: Type argsType = args.GetType();
   2: PropertyInfo piResults = argsType.GetProperty("Result");
   3: object result = piResults.GetValue(args, null);

This works great if the object you are trying to retrieve is just a simple object.  However, what if the object in question is a collection of some sort?  This does not work because the results of type object are useless.  The key to solving this issue is to use the IEnumerable interface.  Here is the code to solve my issue:

   1: Type argsType = args.GetType();
   2: PropertyInfo piMessageList = argsType.GetProperty("Result");
   4: IEnumerable Messages = (IEnumerable)piMessageList.GetValue(args, null);
   6: Type objType;
   7: PropertyInfo objResults;
   8: foreach (object thisMsg in Messages)
   9: {
  10:     objType = thisMsg.GetType();
  11:     objResults = objType.GetProperty("Message");
  12:     Processmessage(objResults.GetValue(thisMsg, null).ToString());
  13: }

Notice on line 4 I’m casting the results from the GetValue method to an IEnumerable.  From there I can run through the objects and use reflection to pull out the individual properties.  Not the cleanest approach, but it works well if you are in a situation where the type of your results are not known to the consumer.

Posted in Labels: , |