17

In C# we can convert an enum to an int by static typecasting as shown below:

int res = (int)myEnum;

Is any other way to do this conversion?

ono2012
  • 4,967
  • 2
  • 33
  • 42
MaxRecursion
  • 4,773
  • 12
  • 42
  • 76

4 Answers4

22

There are plenty of other ways (including Convert.ToInt32 as mentioned by acrilige), but a static cast is probably the best choice (as far as readability and performance are concerned)

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
  • Just to add the [link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#explicit-enumeration-conversions) to the C# 6.0 documentation – Pimenta Aug 16 '21 at 18:13
10

Best would be:

int res = Convert.ToInt32(myEnum);

OR a static cast

int res = (int)myEnum;
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
4

Here is an example enum:

public enum Books
{
    cSharp = 4,
    vb = 6,
    java = 9
}

Then the code snippet to use would be:

Books name = Books.cSharp;
int bookcount = Convert.ToInt32(name);
ono2012
  • 4,967
  • 2
  • 33
  • 42
Rahul
  • 5,603
  • 6
  • 34
  • 57
0

you can do

int enumInt = Convert.ToInt32(yourEnum);

masterlopau
  • 563
  • 1
  • 4
  • 13