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 )
You can explicitly type cast an int to a particular enum type, as shown below.
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.
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.
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.
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.
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