Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert enum to int

Tags:

c#

enums

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?

like image 387
MaxRecursion Avatar asked Feb 11 '13 06:02

MaxRecursion


2 Answers

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)

like image 198
Richard Szalay Avatar answered Oct 03 '22 20:10

Richard Szalay


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);
like image 30
Rahul Avatar answered Oct 03 '22 21:10

Rahul