Search code examples
c#.netforeachreflectionproperties

Foreach can't be used for variables of type "PropertyInfo" because "PropertyInfo" has no defintion for "GetEnumerator"


I want to iterate throug a Dictionary<string, object> with a foreach loop. First I get all of the items with reflection. And when item.Name is not settings the program goes in the else path. Here item is of type Dictionary<string, object> during runtime. But I get an error because at compile time item is of type PropertyInfo. Is it possible to loop over the Dictionary?

PropertyInfo[] propertyInfos = MyResponse.MyDocument.GetType().GetProperties();
foreach (var item in propertyInfos)
{
    if (item.Name != "settings")
    {
         // do something
    }
    else
    {
         foreach (var setting in item) // Compiler Error CS1579
         {
              // do something else
          }
     }
}

Compiler Error CS1589 at Microsoft Learn

I'm using .NET Framework 4.5.


Solution

  • Here item is of type Dictionary<string, object> during runtime.

    No it isn't; it is of type PropertyInfo (or perhaps some more concrete subclass like RuntimePropertyInfo). If you want the value of the property against a specific object (assuming non-static), then you get to get the value, via item.GetValue(MyResponse.MyDocument). That gives you object, though; if you know that the value is Dictionary<string, object>, you can cast:

    var untyped = item.GetValue(MyResponse.MyDocument);
    var typed = (Dictionary<string, object>)untyped;
    

    now you can use the typed features, such as foreach