19

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?

2

4 Answers 4

24

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Just to add the link to the C# 6.0 documentation
10

Best would be:

int res = Convert.ToInt32(myEnum);

OR a static cast

int res = (int)myEnum;

Comments

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

Comments

0

you can do

int enumInt = Convert.ToInt32(yourEnum);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.