C # enums as int

Is there a way to make my enum default as ints? so I don’t need to invent it everywhere? I mainly use it as a list of const values.

+3
source share
3 answers

No.

If you really need a group of int constants, use a static class:

public static class Constants {
  public const int ConstantOne = 42;
  public const int ConstantTwo = 42;
  ...
}
+8
source

No, if you declared enum, their default value is an enumeration, and an explicit cast is required to get the int value. If you use the enum value as const, why not use the const values? If you need some kind of separation, you can create a structure that contains nothing but these const values.

+7
source

, ,

public static int ToInt(this Enum obj)
{
   return Convert.ToInt32(obj);
}

, .

var t = Gender.male;
var r = t.ToInt();
+1

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


All Articles