Yannis Krz Yannis Krz - 1 year ago 60
C# Question

Pass string value as a type

I have some enumerations, like that: OneEnum, TwoEnum, ThreeEnum, etc.
Depending on the user's input I want to print the content of the corresponding enumeration.

I use a foreach like the one below to do that.

foreach(OneEnum i in Enum.GetValues(typeof(OneEnum)))
Console.WriteLine("{0}", i);

Since I have many different enumerations, I am trying to create a way to do that without having many if statements where I check the enumeration type.

At some point I get a string like that
enumType = "OneEnum"
enumType = "TwoEnum"
etc, which is the type of the enumeration.

Is there a way to pass the string's value as the enumeration type in the foreach?


Answer Source

You are looking for Type.GetType

foreach(Enum i in Enum.GetValues(Type.GetType("Your.Namespace.OneEnum"))
    Console.WriteLine("{0}", i);

Live example: http://rextester.com/KXFEX78943

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download