Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums - All options value

Tags:

Is there a way to add an "All values" option to an enum without having to change its value every time a new value is added to the enum?

[Flags]  public enum SomeEnum {     SomeValue =  1,     SomeValue2 = 1 << 1,     SomeValue3 = 1 << 2,     SomeValue4 = 1 << 3,     All = ? } 

Update:

Ended up inheriting from long and using long.MaxValue for All option.

like image 394
Gil Stal Avatar asked Dec 13 '11 11:12

Gil Stal


People also ask

What is the value of enums?

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.

Can multiple enums have same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

What is enum default value?

The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero.


2 Answers

Since you should define the empty value in a Flags enum such as None = 0, the simplest way of defining the Allvalue is by simply inverting all the bits inNone`.

[Flags] enum MyEnum {    None = 0,    A = 1,    B = 2,    C = 4,    ...    All = ~None } 

Note that ~0 instead of ~None will not work for unsigned backing types as that is -1, which is not a valid value for unsigned.

Edit: Answer was modified to use an inverted None instead of an explicit constant such as 0x7FFFFFFF or ~0, as this also works for unsigned

like image 168
Anders Forsgren Avatar answered Oct 29 '22 22:10

Anders Forsgren


It should be like this:

[Flags]  public enum SomeEnum {     SomeValue =  1,     SomeValue2 = 1 << 1,     SomeValue3 = 1 << 2,     SomeValue4 = 1 << 3,     All = SomeValue | SomeValue2 | SomeValue3 | SomeValue4 } 
like image 33
Dmitriy Konovalov Avatar answered Oct 29 '22 21:10

Dmitriy Konovalov