user1838662
user1838662

Reputation: 523

iterate through an enum type initialized with a string name?

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.

Upvotes: 0

Views: 158

Answers (3)

It'sNotALie.
It'sNotALie.

Reputation: 22794

Enum.GetValues(Type.GetType(yourEnumName, true, true));

Upvotes: 0

Matten
Matten

Reputation: 17631

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

Upvotes: 1

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5833

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();
}

Upvotes: 1

Related Questions