Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum of long values in C#

Tags:

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 } 
like image 992
Matthieu Avatar asked Aug 17 '11 13:08

Matthieu


People also ask

Can enum be long?

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.

How large is an enum in C?

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.

Why is enum 4 bytes?

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.


1 Answers

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; 
like image 93
dlev Avatar answered Oct 08 '22 13:10

dlev