2

I have the following enum:

[Flags]
public enum Permissions
{
    None = 0x0000,
    All = 0xFFFF
}

If either None or All are raised, no other flag should be raised.
How do I check if either None or All are raised and nothing else?

the_drow
  • 18,571
  • 25
  • 126
  • 193
  • 6
    You are not using the `Flags` attribute correctly. The attribute is meant for enums that are implemented as bitmasks, and if your enum were a bitmask, then you wouldn't need to ask this question since `None` would be `0` and `All` would be `0xFFFF`. – mqp May 30 '11 at 20:06
  • http://stackoverflow.com/questions/8447/enum-flags-attribute – Jason Evans May 30 '11 at 20:07
  • If use used Flags correctly then None would have mask 0000...0 and All would have mask 1111...1, which means that `All` corresponds to all flags set and `None` to none flags set. – Alex Aza May 30 '11 at 20:09

2 Answers2

6

In a flags enum, None should be zero, and All should be the cumulative bitwise sum. This makes the maths pretty easy, then:

if(value == Permissions.None || value == Permissions.All) {...}

maybe written as a switch if you prefer...

However, in the general case, you can test for a complete flags match (against any number of bits) with:

if((value & wanted) == wanted) {...}

and to test for any overlap (i.e. any common bits - wanted needs to be non-zero):

if((value & wanted) != 0) {...}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks! This is a completely foreign concept to me but a very cool feature of the language. Thanks for the clarification. Never did much AND'ing or OR'ing in Java :) – fIwJlxSzApHEZIl Nov 17 '12 at 04:33
0
if(value|Permissions.None)==Permissions.None;

This can check Permissions.None is raised. The rest can be done in the same manner.

Justin
  • 676
  • 1
  • 8
  • 24