Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arithmetic operations on enum values

Tags:

c#

.net

enums

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?

like image 301
gluk47 Avatar asked Mar 20 '12 09:03

gluk47


People also ask

What is the purpose of values () method in enum?

What is the purpose of the valueOf() method in the enum? The Java compiler internally adds the valueOf() method when it creates an enum. The valueOf() method returns the value of given constant enum.

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

What are enum values?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


1 Answers

The following operators can be used on values of enum types: ==, !=, <, >, <=, >=, +, -, ^, &, |, ~, ++, --, sizeof.

like image 176
Kirill Polishchuk Avatar answered Sep 21 '22 11:09

Kirill Polishchuk