How to iterate the List in Reflection

Others have suggested casting to List but I will assume that this won't work for you... if you had access to the Student class, you wouldn't be using reflection to begin with. So instead, just cast to IEnumerable and then inside your loop, you'll have to use reflection again to access whatever properties you want off of each item in the collection.

var collection = (IEnumerable)studentPro.GetValue(studentObj,null)


Try this

IEnumerable<Student> collection = (IEnumerable<Student>)studentPro.GetValue(studentObj,null);

You just need to cast it:

var collection = (List<Student>) studentPro.GetValue(studentObj,null);

The value returned to you and stored in var is of type object. So you need to cast it to List<Student> first, before trying looping through it.

RANT

That is why I personally do not like var, it hides the type - unless in VS you hover on it. If it was a declared with type object it was immediately obvious that we cannot iterate through it.


UPDATE

Yes its good. But casting should be done with reflection. In reflection we dont know the type of List. We dont know the actual type of the studentObj

In order to do that, you can cast to IEnumerable:

var collection = (IEnumerable) studentPro.GetValue(studentObj,null);

The way you tried is, is the right one. You just need to fix your code and cast the return value from GetValue:

var collection = (List<Student>)studentPro.GetValue(studentObj,null);

foreach(var item in collection)
{
     if(item.StudentID == 33)
         //Do stuff
}

Tags:

C#

Reflection