What arithmetic operations are supported on c# enums? Surprisingly, I was unable to find it via neither google, nor wikipedia and stackoverflow.
Can I add two enum values without any cast ? Add arbitrary constant to a value or subtract it? Or does enum guarantee that a value of that type is always one of the defined enum values or their bitmask?
class ... {...
enum WeekDays : byte { Sun = 1, Mon = 2, Tue = 3, /* and so on*/ Sat = 7 };
public static bool IsWeekend (WeekDays _d) {
/// Can I be sure here that _d has value from 1..7? May it be any of 0..255?
}
I know about bitwise operations, It seems reasonable to support them for representing flags.
Wikipedia tells us, my sample also allows _d - 1
or WeekDays.Tue - WeekDays.Mon
, that can be useful for strictly ordered sequential enums, but I cannot find any standard reference, could you, please, point me?
The following operators can be used on values of enum types: ==
, !=
, <
, >
, <=
, >=
, +
, -
, ^
, &
, |
, ~
, ++
, --
, sizeof
.
If you want to use an arithmetic operations, do not use enums
, use numbers
. Enums
is a naming convension for numeric values to make them more human readable and allow having a combination of them. That is actually the reason that you didn't find anything about that on internet, cause it's not soemthing that should be done with enums
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.