Alan Alan - 14 days ago 6
C# Question

Returning the text (string value) of an enum value

I have this enum:

public enum Lang
{
English = 0,
Romaji = 1,
Kana = 2,
Kanji = 3,
}


I know I can write:

var a = Lang.English
var b = a;


and set
b
to be equal to 0. However is there any way that I can set
b
equal to
"English"
if given
a
?

Answer

Essentially an enum is a set of named constants. So instead of using the constants, you use their names to make your code more readable.

The value of b would be equal to the named constant Lang.English and it's type wouldn't be of a string but it would be of Lang. So casting b to an int, you would get 0.

However is there any way that I can set b equal to "English" if given a?

Yes, you could try the following:

string b = Enum.GetName(typeof(Lang),Lang.English);

For a demo, please have a look here