Iterating Through a Collection Using Reflection
Posted On Tuesday, March 10, 2009 at at Tuesday, March 10, 2009 by Ben HI 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");
3:
4: IEnumerable Messages = (IEnumerable)piMessageList.GetValue(args, null);
5:
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: }