-1
[ Flags ]
public enum StatusType { a,b,c,d,e,f,g }

StatusType m_StatusType = a | b;

If ( m_StatusType only contains a and b )  // I need help here
{ 

}

Hi,

I need some help on comparing flags. How can I know if a flag enum variable contains only some particular values?

DVN
  • 114
  • 1
  • 9
  • 1
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Roman Marusyk Aug 18 '16 at 23:36
  • `(m_ StatusType & (a | b)) == a | b` – Mathias R. Jessen Aug 18 '16 at 23:37
  • Please see the marked duplicate for a _thorough_ discussion of enum types that use `[Flags]` and how to use them. If you find yourself with some remaining confusion, post a new question that includes a good [mcve] that shows clearly what trouble you're having. Describe what the code does, what you want it to do instead, and what _specifically_ you're having trouble figuring out. – Peter Duniho Aug 18 '16 at 23:42
  • @DVN then Peter is right and you should read this http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c – Gerardo Grignoli Aug 18 '16 at 23:47

2 Answers2

1

First off, when defining a flags enum, each flag should represent a single bit in the enum:

enum X { a = 1, b = 2, c = 4, d = 8 }

This allows you to combine flags as well:

CandD = 12, //has both c and d flags set.

Or if you have a lot of them:

enum X { 
  a = 1 << 0, 
  b = 1 << 1, 
  c = 1 << 2, 
  d = 1 << 3,
  ...
  CAndD = c | d
}

You can use a simple equality comparison to test if only certain flags are set.

public bool ContainsOnly(X value, X flags) 
{
     return value == flags;
}

public bool ContainsOnlyCandD(X value) 
{
     return value == (X.c | X.d);
}

public bool ContainsBothCandDButCouldContainOtherStuffAsWell(X value) 
{
     return (value & (X.c | X.d)) == (X.c | X.d);
}
Bas
  • 26,772
  • 8
  • 53
  • 86
1

Firstly, your flags should be created as such:

[Flags]
public enum StatusType
{
    None = 0
    A = 1,
    B = 2,
    C = 4,
    D = 8,
    E = 16,
    F = 32,
    G = 64
}

You can then assign as such:

var statusType = StatusType.A | StatusType.B;

And test it as such:

if (statusType.HasFlag(StatusType.A))
{
    //A is defined
}
João Lourenço
  • 736
  • 5
  • 8
  • I just want to elaborate on why this answer works, for OP's benefit (and any future people). Each of those enum values are being assigned a value in binary that only contains a single 1, and the rest are 0. `1 = 1, 2 = 01, 4 = 100, 8 = 1000, 16 = 10000, etc`. `|` is the bitwise or operator, and doing something like `1 | 4` yields the binary number `101`. You can then compare them using bitwise and `&` to see if the value is present. `101 & 10 = 000`, but `101 & 100 = 100`. Hopefully the other explanations on this page make more sense. – Cody Aug 18 '16 at 23:46