Arithmetic operations with enum values

What arithmetic operations are supported in C # enumerations? Surprisingly, I could not find it using google, nor with wikipedia and stackoverflow.

Is it possible to add two enumeration values without any actors ? Add arbitrary constant to value or subtract it? Or does enum guarantee that a value of this type is always one of the defined enumeration values โ€‹โ€‹or their bitmasks?

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 to represent flags.

Wikipedia tells us that my example also allows _d - 1or WeekDays.Tue - WeekDays.Mon, which may be useful for strictly ordered consecutive enumerations, but I cannot find a standard link, could you point me to?

+5
source share
2 answers

When enumeration value types can be used following operators: ==, !=, <, >, <=, >=, +, -, ^, &, |, ~, ++, --, sizeof.

+5
source

If you want to use arithmetic operations, do not use enums, use numbers. enums- This is a designation for numerical values, in order to make them more understandable to humans and to allow them to have a combination. This is actually the reason why you did not find anything about it on the Internet, because it should not be done using enums.

0
source

All Articles