From another layer in an application I can get back the name of the enum type and an integer value. How can I use this data to get the string representation of that value for that enum.
For example, if I have an enum:
public enum Cheese
{
Edam = 1,
Cheddar = 3,
Brie = 201,
RedLeicester = 1001
}
and the data I have available is
string dataType = "Cheese";
int dataValue = 3;
How can I get the result:
"Cheddar"
In addition to the name of enum itself you should know namespace and assembly that enum is declared at. Assuming you run code below in assembly where enum is defined and all your enums are defined in the same namespace you know at compile time, you can do it like that:
string dataType = "Cheese";
int dataValue = 3;
var enumType = Type.GetType("Namespaces.Of.Your.Enums." + dataType);
var name = Enum.GetName(enumType, dataValue);
If your enum is in another assembly than this code is running at - you will need to provide assembly qualified name of your enum type (again with namespace).
Type t = Type.GetType(dataType)
string value = Enum.GetName(t, dataValue)
should do the trick (uncompiled, on subway)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With