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;
}
CA1069: Enums should not have duplicate values.
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.
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 }
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.
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
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;
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With