Is there a way to iterate (through foreach preferably) over a collection using reflection? I\'m iterating over the properties in an object using reflection, and when the pr
If you're not using an instance of the object but rather a Type, you can use the following:
// type is IEnumerable
if (type.GetInterface("IEnumerable") != null)
{
}
I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. string
for instance is also IEnumerable and will iterate over the characters.
Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable).
public bool isCollection(object o)
{
return typeof(ICollection).IsAssignableFrom(o.GetType())
|| typeof(ICollection<>).IsAssignableFrom(o.GetType());
}
I would look at the Type.FindInterfaces method. This can filter out the interfaces implemented by a given type. As in PropertyInfo.PropertyType.FindInterfaces(filterMethod, filterObjects). You can filter by IEnumerable and see if any results are returned. MSDN has a great example in the method documentation.