How can I test whether a class member is a list when I don't know it's exact type? And how do I then iterate over it?
myc is an instance of MyClass
using System.Reflection;
public class MyClass {
public sometype somename { get; set; }
public List<double> doubles { get; set; }
public List<string> strings { get; set; }
}
foreach(PropertyInfo pi in MyClass.GetProperties()) {
if (pi.GetValue(myc, null) is List<???>){ <--- what should this be?
foreach(object obj in pi.GetValue(myc, null)) { <---- doesn't work
}
var l = pi.GetValue(myc, null) as List<???> <---- doesn't work
}
}
If all you want to do is enumerate the values, you could test for the non-generic IEnumerable
instead:
object value = pi.GetValue(myc, null);
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (object obj in enumerable)
{
...
}
}
Note that that will iterate over the characters in a string, as string
implements IEnumerable<char>
. You may want to hard-code against that.
If you're happy with any IList
implementation (including List<T>
), you could substitute IList
for IEnumerable
above.
Note that basically this is avoiding getting into generics - detecting and using generics within reflection is a messy business.
See more on this question at Stackoverflow