While learning the flag technique, I encountered some problem, hereby I’m showing this example using C#, with Enum:
[Flags]
enum PermissionTypes : byte
{
None = 0x0,
Read = 0x1,
Write = 0x2,
Modify = 0x4,
Delete = 0x8,
Create = 0x10,
All = Read | Write | Modify | Delete | Create
}
To check hasFlag property:
if((value & mask) == mask) {...}
But when ‘hasFlag’ applied on both ‘None’ and ‘Read’:
Denote x = Current_Permission_Setting,
x & PermissionTypes.None = always false
x & PermissionTypes.Read = always true IFF
(cont’) IFF x = {ODD byte value}
Question: What are the perfect sets of flag values that are safe to be used?
Reference:
Here’s the full example.
As @antlersoft says in the comments, you can’t really use
NONEas a bitflag.The rest of your flags make sense. You do need to use the powers of 2 to get 1 bit per flag.
It doesn’t make sense to test for “Has READ and NONE” set, anyway, since NONE implies READ is not set.
The problem you describe with odd values of X doesn’t seem to make sense. The value will only be odd if bit 1 is set. If you are using your flags consistently, bit 1 will only be set if READ is true.