Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the numeric value from the Enum?

For example System.Net.HttpStatusCode Enum, I would like to get the HTTP Status Codes instead of the HTTP Status Text. System.Net.HttpStatusCode.Forbidden should return 403 instead of "Forbidden".

How can I extract the value?

like image 406
kurozakura Avatar asked Oct 08 '09 22:10

kurozakura


People also ask

Can enums be assigned numerical values?

Can one assign custom numeric values to enum elements in Java? Not directly as you've written, i.e., where an enum value equals a number, but yes indirectly as shown in Ben S's link.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can enums contain numbers?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


2 Answers

For the majority of Enum's simply cast to the base type which is int32.

int value = (int)System.Net.HttpStatusCode.Forbidden; 
like image 174
JaredPar Avatar answered Oct 05 '22 14:10

JaredPar


You can just cast it to an integer!

int code = (int)enumVariable 
like image 27
Erich Avatar answered Oct 05 '22 14:10

Erich