MaxRecursion
MaxRecursion

Reputation: 4903

How to convert enum to int

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?

Upvotes: 19

Views: 41722

Answers (4)

Rahul
Rahul

Reputation: 5636

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);

Upvotes: 4

masterlopau
masterlopau

Reputation: 563

you can do

int enumInt = Convert.ToInt32(yourEnum);

Upvotes: 0

Vishal Suthar
Vishal Suthar

Reputation: 17194

Best would be:

int res = Convert.ToInt32(myEnum);

OR a static cast

int res = (int)myEnum;

Upvotes: 10

Richard Szalay
Richard Szalay

Reputation: 84804

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)

Upvotes: 24

Related Questions