Question

Is it possible to iterate through a enum without knowing its type first?

Say I pass in a string name that represents the type of the enum to a method.

I would then somehow need to get the enum type from that string name and iterate through the collection to extract the names/values contained in the enum.

Was it helpful?

Solution

You can use reflection to do it

List<KeyValuePair<string, object>> GetEnumInfo(string name)
{
    var type = Type.GetType(name);
    return Enum.GetValues(type)
            .Cast<object>()
            .Select(v => new KeyValuePair<string, object>(Enum.GetName(type, v), v))
            .ToList();
}

OTHER TIPS

Yes, you can access the names and values of a enum if you know the type. For example see the following code snippet:

string enumTypeName = "qualified enum type name";

var enumType = Type.GetType(enumTypeName);

var values = Enum.GetValues(enumType);
var names  = Enum.GetNames(enumType);

Now you can easily iterate over values and names

Enum.GetValues(Type.GetType(yourEnumName, true, true));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top