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;
}
dtb
  • 213,145
  • 36
  • 401
  • 431
zrabzdn
  • 995
  • 2
  • 14
  • 33

3 Answers3

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

Nico
  • 12,493
  • 5
  • 42
  • 62
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;
dtb
  • 213,145
  • 36
  • 401
  • 431
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();
TGH
  • 38,769
  • 12
  • 102
  • 135