Categories
c# casting enums int

Get int value from enum in C#

2199

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

In the Questions class I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value off the enum so I can do something like this Questions.Get(Question.Role)?

3

  • 43

    For the other way around: cast-int-to-enum-in-c-sharp.

    – nawfal

    Jun 9, 2013 at 11:54

  • 14

    I know I’m late to the party, but instead of defining your method as get(int foo) you can define it as get(Question foo) then do your casting inside the method, the you can call your method as Questions.Get(Question.Role)

    – Joe

    Feb 7, 2017 at 15:10

  • try this: int int_Choose = (int) Question.Role;

    – گلی

    Jul 18, 2021 at 7:35

2781

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;

8

  • 25

    @Harry it isn’t true. You can create Enumeration without casting, it is not required. and I only assign number in special cases, most of the time, I leave it as default value. but you can do enum Test { Item = 1 } and see that 1 == (int)Test.Item is equal.

    – Jaider

    Jun 28, 2012 at 20:47

  • 47

    @Jaider (int)Test.Item That is a cast! () is the explicit cast operator.

    – Sinthia V

    Jul 26, 2012 at 19:02

  • 54

    @Sinthia V he said you can create it without casting, which is correct

    Aug 17, 2012 at 18:30

  • 8

    If the underlying type for enum Question was not int but long this cast will truncate Roles integral value!

    – quaylar

    Oct 29, 2013 at 16:14

  • 2

    When you accept an Enum as a parameter, you know is only a fixed number of possible integral values you can get. On the other hand, if you take simply an int, then you have to validate if that int is within the accepted values., thus complicating the code. You can always override your signatures like “` public void MyMethod(int x) { // do something with x } public void MyMethod(Enum x) { this.MyMethod((int) x); } ““

    – percebus

    Aug 18, 2015 at 16:52

361

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.

11

  • 45

    This technique proved its worth to me when dealing with a generic type where T:enum (actually T:struct, IConvertible but that’s a different story).

    – aboy021

    Jul 5, 2011 at 23:20

  • 2

    How would you modify this to print out the hexadecimal value of side? This example shows the decimal value. The problem is that var is of type object, so you need to unbox it and it gets messier than I would like.

    Nov 9, 2012 at 2:15

  • 1

    If you want to convert to int try (in case of an enum Sides : int) […] object val = Convert.ChangeType(side, typeof(int)); […]

    – theLaw

    Jun 9, 2014 at 16:05


  • 3

    @TimAbell All I can really say is that we found that dynamically compiled aspx pages (where you have to deploy the .cs files to the live server) were assigning the integers differently to each value. That meant that serialised objects one one machine, were deserialising with different values on a different machine and effectively getting corrupted (causing hours of confusion). We raised it with MS and I seem to recall they said that the autogenerated integers were not guaranteed to be the same when built across different framework versions.

    – NickG

    Mar 24, 2015 at 9:42

  • 9

    @TimAbell On a separate occasion, a developer deleted an obsolete/unused Enum value causing all other values in the sequence to be out by one. As such, our coding standards now require that IDs are always specified explicitly, otherwise adding/deleting or even auto-formatting the code (e.g. sorting alphabetically) will change all the values causing data corruption. I would strongly advise anyone to specify all Enum integers explicitly. This is ultra-important if they correlate to externally (database) stored values.

    – NickG

    Mar 24, 2015 at 9:46

216

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.

12

  • 35

    I’d use static readonly int because constants are compiled into their hard values. See stackoverflow.com/a/755693/492

    – CAD bloke

    May 15, 2013 at 23:16

  • 108

    This solution actually doesn’t provide the real benefit of strongly typed enums. If I only wanted to pass a GameState-enum-parameter to a specific method for example, the compiler shouldn’t allow me to pass any int-variable as a parameter.

    – thgc

    Apr 12, 2014 at 18:24

  • 13

    @CADBloke which is precisely why you would use const and not static readonly because every time you compare static readonly you’re making a method call to get the value of the variable whereas with a const you’re comparing two value types directly.

    – blockloop

    Aug 14, 2014 at 17:11

  • 3

    @brettof86 Yes, a const would be faster, if the compilation limitation will never be problem then it’s all good.

    – CAD bloke

    Aug 15, 2014 at 10:57

  • 3

    @Zack I didn’t explain that very well, by compilation limitation I mean that the value is hard-coded when you compile it so any change to that value would require that all assemblies using it need to be recompiled. I’m inclined to agree with you about usage because changing the values would have far-reaching implications.

    – CAD bloke

    Apr 22, 2015 at 21:53