Search code examples
c#enumspropertyinfo

Get number of enum values from instance


I'm trying to loop through all of the enums in an object and for each enum, I need to get the number of values for its particular type. So far I have the following code:

var enumProps = testObj.GetType().GetProperties().Where(p => p.PropertyType.IsEnum);

foreach (var prop in enumProps)
{
       var propType = prop.GetType(); 

       var valueCount = Enum.GetValues(typeof(propType)).Length; // <-- error

}

The problem is that when I pass propType to typeof, I get the following error:

propType is a variable but used as a type.

Anyone see where I'm going wrong here?


Solution

  • GetType produces the type of prop, which is fixed (i.e. PropertyInfo reflection class). You need to use PropertyType member, like this:

    foreach (var prop in enumProps) {
           var propType = prop.PropertyType; 
           var valueCount = Enum.GetValues(propType).Length;
    }
    

    Demo.

    Note that typeof operator is not necessary, because propType is already a System.Type that you need.