List best practices

I can not choose between two conversion methods. 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; } 
+6
source share
3 answers

In addition to @dtb

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

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

Greetings

+3
source

If you have an enumeration, for example

 enum MyEnum { Foo, Bar, Baz, } 

and the meaning of this listing, such as

 MyEnum value = MyEnum.Foo; 

then the best way to convert the value to int is

 int result = (int)value; 
+3
source

I would choose the third option in the mix as 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(); 
+2
source

Source: https://habr.com/ru/post/957005/


All Articles