15

I can't select between two methods of converting. What is the best practice by converting from enum to int

1:

public static int EnumToInt(Enum enumValue) { return Convert.ToInt32(enumValue); } 

2:

public static int EnumToInt(Enum enumValue) { return (int)(ValueType)enumValue; } 
0

3 Answers 3

5

In addition to @dtb

You can specify the int (or flag) of your enum by supplying it after the equals sign.

enum MyEnum { Foo = 0, Bar = 100, Baz = 9999 } 

Cheers

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

Comments

4

If you have an enum such as

enum MyEnum { Foo, Bar, Baz, } 

and a value of that enum such as

MyEnum value = MyEnum.Foo; 

then the best way to convert the value to an int is

int result = (int)value; 

Comments

3

I would throw a third alternative into the mix in the form of an extension method on Enum

public static int ToInt(this Enum e) { return Convert.ToInt32(e); } enum SomeEnum { Val1 = 1, Val2 = 2, Val3 = 3, } int intVal = SomeEnum.ToInt(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.