Get enum name from a value in C#
This post will discuss how to get the enum member name from the associated constant value in C#.
1. Using Enum.GetName() method
The standard method to retrieve the name of the constant having the specified value is to use the Enum.GetName() method. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 } public static void Main() { int value = 5; string day = Enum.GetName(typeof(Days), value); Console.WriteLine(day); } } /* Output: Friday */ |
2. Using Casting
To get the corresponding constant value from an enumeration member, use casting. The following example demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 } public static void Main() { int value = 5; var day = (Days)value; Console.WriteLine(day); } } /* Output: Friday */ |
That’s all about getting an enum name from a value in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)