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.
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.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
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.
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 in
None`.
[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
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 }
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