Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to int best practice [duplicate]

Tags:

c#

enums

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;
}
like image 300
zrabzdn Avatar asked Oct 30 '13 05:10

zrabzdn


People also ask

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

When to use enum in C#?

Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.

What are enumerations in C#?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy. enum Season { Spring, Summer, Autumn, Winter }

Is enum value type C#?

C# enum is a value type with a set of related named constants often referred as an enumerator list. The C# enum keyword is used to declare an enumeration. It is a primitive data type, which is user-defined.


3 Answers

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

like image 170
Nico Avatar answered Oct 22 '22 02:10

Nico


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;
like image 27
dtb Avatar answered Oct 22 '22 02:10

dtb


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();
like image 2
TGH Avatar answered Oct 22 '22 00:10

TGH