If you do this by listing [Flags], you can assign a different bit value (1, 2, 4, 8, 16 ...) for each value listed. You can then use a bitwise action to determine if a value is one of many possible values.
So, to make sure it is C, D or F:
bool IsCDF(MyEnum enumValue) { return((enumValue & (MyEnum.C | MyEnum.D | MyEnum.F)) != 0); }
Note that this will not work for a value of 0 (in your example, βAβ), and you should be careful that all enumeration values ββallow unique bit values ββ(that is, non-zero permissions for two).
The advantages of this approach are as follows:
- typically, a single CPU command will be executed, while three separate if-checks will require 3 or more instructions (depending on your target platform).
- You can pass a set of values ββthat you want to test using an enumeration value (integer) instead of having to use lists of enumeration values.
- You can do many other useful things with bitwise operations that would be awkward and slow with conventional numerical / comparative approaches.
Jason williams
source share