Search code examples
c#reflectionienumerablevar-dumppropertyinfo

PropertyInfo.GetValue(object) fails with IEnumerable<T> [C#, Reflection]


I have the following problem:
I am currently writing the c# equivalent of PHP's var_dump-method. It works perfectly with 'simple' classes and structures (and even with arrays).
My only problem is when it comes to other IEnumerable<T>, like List<T> etc:

The debugger is throwing an TargetParameterCountException. My code looks as follows:

Type t = obj.GetType(); // 'obj' is my variable, i want to 'dump'
string s = "";
PropertyInfo[] properties = t.GetProperties();

for (int i = 0; i < properties.Length; i++)
{
    PropertyInfo property = properties[i];

    object value = property.GetValue(obj); // <-- throws exception

    if (value is ICollection)
    {
        // Code for array parsing - is irrelevant for this problem
    }
    else
        s += "Element at " + i + ": " + value.GetType().FullName + " " + value.ToString() + "\n";
}

return s;

I know, that i can somehow fetch indices with PropertyInfo.GetIndexParameters(), but I did not figured out, how to use it correctly.

Edit: I also want to note that I neither know the size of the IEnumerable, nor the Type T at compile time.


Solution

  • This has nothing to do with the type implementing IEnumerable. Rather it's about the type having an indexer. Indexers are considered properties, but they're special properties that need to be given the parameter of the index when getting their value. If you don't, it errors as you're seeing here.

    You can use GetIndexParameters() and check the count of the returned array to determine if the property is an indexer. This will let you either skip that property (which is what I assume you'll want to do here), or use it to get its values.