Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why enums require an explicit cast to int type?

Tags:

There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type ) 

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type ) 
like image 332
Joan Venge Avatar asked Jan 18 '11 19:01

Joan Venge


People also ask

Can you cast an int to an enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Can enum be treated as int?

An Enum value cannot be treated as an int by default because then you would be able to provide any integer and there would be no compile time check to validate that the provided integer does in fact exist as a value in the Enumeration.

Which data type can be used in enum?

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.

Can enum be Typecasted?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.


1 Answers

There are two primary and inconsistent uses of enums:

enum Medals { Gold, Silver, Bronze }  [Flags] enum FilePermissionFlags {     CanRead = 0x01,     CanWrite = 0x02,     CanDelete = 0x04 } 

In the first case, it makes no sense to treat these things as numbers. The fact that they are stored as integers is an implementation detail. You can't logically add, subtract, multiply or divide Gold, Silver and Bronze.

In the second case, it also makes no sense to treat these things as numbers. You can't add, subtract, multiply or divide them. The only sensible operations are bitwise operations.

Enums are lousy numbers, so you should not be able to treat them as numbers accidentally.

like image 57
Eric Lippert Avatar answered Oct 19 '22 06:10

Eric Lippert