Why does this declaration,
public enum ECountry : long { None, Canada, UnitedStates }
require a cast for any of its values?
long ID = ECountry.Canada; // Error Cannot implicitly convert type 'ECountry' to 'long'. // An explicit conversion exists (are you missing a cast?)
And is there a way to get a long value directly from the enum, besides casting?
This would not work either, for example:
public enum ECountry : long { None = 0L, Canada = 1L, UnitedStates=2L }
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.
The size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.
The issue is not that the underlying type is still int
. It's long
, and you can assign long
values to the members. However, you can never just assign an enum
value to an integral type without a cast. This should work:
public enum ECountry : long { None, Canada, UnitedStates = (long)int.MaxValue + 1; } // val will be equal to the *long* value int.MaxValue + 1 long val = (long)ECountry.UnitedStates;
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