NiloCK
NiloCK

Reputation: 621

How to get the list of Enum properties of a class?

Closely related to How to get the list of properties of a class?, I've gotten as far as that question goes but I'm interested in knowing which of the returned properties are enumerations. My first (unlikely) guess was along the lines of:

foo A;

foreach (var property in A.GetType().GetProperties())
{
    if (property.PropertyType is Enum)
        //Celebrate
}

This did not work. It's valid, but Visual Studio was even able to warn in advance that "The given expression is never of the provided ('System.Enum') type".

To my understanding, C# Enums are wrappers over top of primitive counting types (defaulting with int, but also possibly byte, short, etc). I can easily test to see of the properties are of these types, but that will lead me to a lot of false positives in my search for Enums.

Upvotes: 2

Views: 2536

Answers (2)

Georg
Georg

Reputation: 5771

You are almost there. Just use

if (property.PropertyType.IsEnum)
    // Celebrate

In .NET 4.5, you might need to get a TypeInfo object from the property type.

Upvotes: 9

SLaks
SLaks

Reputation: 887305

property is a PropertyInfo object.
PropertyInfo doesn't inherit Enum, so that can never be true.

You want to check the PropertyType – the Type object describing the property's return type.

if (property.PropertyType is Enum) won't work either, for the same reason – Type doesn't inherit Enum.

Instead, you need to look at the properties of the Type object to see whether it's an enum type.
In this case, you can just use its IsEnum property; in the more general case, you would want to call IsSubclassOf().

Upvotes: 4

Related Questions