Reputation: 523
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
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
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