Get integer value from enum member name in C#
This post will discuss how to get the constant integer value from the enum member name in C#.
1. Using Casting
We can get the constant integer value simply by casting the enum member name. 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 28 29 |
using System; public class Example { public enum HttpStatusCode { OK = 200, Accepted = 202, MovedPermanently = 301, Redirect = 302, Unauthorized = 401, Forbidden = 403, NotFound = 404, InternalServerError = 500, ServiceUnavailable = 503 } public static void Main() { HttpStatusCode code = HttpStatusCode.Accepted; int value = (int) code; Console.WriteLine(value); } } /* Output: 202 */ |
The default underlying type for an enum is an integer. However, if enum has different underlying types such as uint, short, ushort, long, ulong, etc., it should be cast to the enum’s corresponding type.
2. Using Convert.ChangeType() method
To get the enum’s underlying value, we can use the Convert.GetTypeCode() method. The following code would work for any type of enum.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; public static void Main() { Colors code = Colors.Blue; Object value = Convert.ChangeType(code, code.GetTypeCode()); Console.WriteLine(value); } } /* Output: 4 */ |
3. Using Object.GetHashCode() method
Another way to get the constant value from the enum member name is by calling the GetHashCode() method on the enum member name. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday }; public static void Main() { Days code = Days.Tuesday; int value = code.GetHashCode(); Console.WriteLine(value); } } /* Output: 3 */ |
That’s all about getting an integer value from an enum member name 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 :)