tags:

views:

273

answers:

3
+3  Q: 

C# enums as int

Is there a way i can make my enum defaulted as ints? so i dont need to typecast it everywhere? Basically i am using it as a list of const values.

+7  A: 

No, if you've declared an enum, their default value is as an enum, and an explicit cast is required to get to the int value. If you're using the enum as const values, why not use const values? If you want some separation you could create a struct that contains nothing but these const values.

Timothy Carter
+8  A: 

No.

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

public static class Constants {
  public const int ConstantOne = 42;
  public const int ConstantTwo = 42;
  ...
}
Richard
+1  A: 

If you really want to do that, you could create an extension method like the following for enums

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

Then you could use it like the following

var t = Gender.male;
var r = t.ToInt();
seanlinmt