SOLUTION:
int enumValue = 2; // The value for which you want to get string
string enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);
Also, using GetName is better than Explicit casting of Enum.
[Code for Performance Benchmark]
Stopwatch sw = new Stopwatch (); sw.Start (); sw.Stop (); sw.Reset ();
double sum = 0;
int n = 1000;
Console.WriteLine ("\nGetName method way:");
for (int i = 0; i < n; i++) {
sw.Start ();
string t = Enum.GetName (typeof (Roles), roleValue);
sw.Stop ();
sum += sw.Elapsed.TotalMilliseconds;
sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Getname method casting way: {sum / n}");
Console.WriteLine ("\nExplicit casting way:");
for (int i = 0; i < n; i++) {
sw.Start ();
string t = ((Roles)roleValue).ToString ();
sw.Stop ();
sum += sw.Elapsed.TotalMilliseconds;
sw.Reset ();
}
Console.WriteLine ($"Average of {n} runs using Explicit casting way: {sum / n}");
[Sample result]
GetName method way:
Average of 1000 runs using Getname method casting way: 0.000186899999999998
Explicit casting way:
Average of 1000 runs using Explicit casting way: 0.000627900000000002
nameof(EnumDisplayStatus.Visible)
Hope it helps somebody – Gabriel Marius Popescuvar x = MyEnum.Visible; nameof(x)
would produce"x"
, not"Visible"
. – Devin Burke