Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an enum name from the name of the enum type and an int [duplicate]

Tags:

c#

enums

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"
like image 700
Kaine Avatar asked Sep 12 '25 00:09

Kaine


2 Answers

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).

like image 87
Evk Avatar answered Sep 13 '25 15:09

Evk


Type t = Type.GetType(dataType)
string value = Enum.GetName(t, dataValue)

should do the trick (uncompiled, on subway)

like image 45
Erik A. Brandstadmoen Avatar answered Sep 13 '25 14:09

Erik A. Brandstadmoen