Get int value from enum in C#

ID : 411

viewed : 448

Tags : c#enumscastingintc#

Top 5 Answer for Get int value from enum in C#

vote vote


Just cast the enum, e.g.

int something = (int) Question.Role; 

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649}; 

you should use

long something = (long)StarsInMilkyWay.Wolf424B; 
vote vote


Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

enum Sides {     Left, Right, Top, Bottom } Sides side = Sides.Bottom;  object val = Convert.ChangeType(side, side.GetTypeCode()); Console.WriteLine(val); 

This should work regardless of the underlying integral type.

vote vote


Declare it as a static class having public constants:

public static class Question {     public const int Role = 2;     public const int ProjectFunding = 3;     public const int TotalEmployee = 4;     public const int NumberOfServers = 5;     public const int TopBusinessConcern = 6; } 

And then you can reference it as Question.Role, and it always evaluates to an int or whatever you define it as.

vote vote


On a related note, if you want to get the int value from System.Enum, then given e here:

Enum e = Question.Role; 

You can use:

int i = Convert.ToInt32(e); int i = (int)(object)e; int i = (int)Enum.Parse(e.GetType(), e.ToString()); int i = (int)Enum.ToObject(e.GetType(), e); 

The last two are plain ugly. I prefer the first one.

vote vote


Question question = Question.Role; int value = (int) question; 

Will result in value == 2.

Top 3 video Explaining Get int value from enum in C#