0

Say I have an enum:

[Flags]
public enum Alpha
{
    NULL = 0,
    A0 = 1,
    A1 = 2,
    A2 = 4,
    A3 = 8
}

And I have the following:

Alpha selected = A0 | A1 | A2

Alpha compare = A1 | A3

I want to check if any of the selected flags are also in the compare flags.

The only way I can think to do this so far is (pseudocode)

foreach(Alpha flag in Enum.GetValues(typeof(Alpha)))
{
    if (selected.HasFlag(flag) && compare.HasFlag(flag))
    {
        return true
    }
}
return false

Is there a more logic-al way to do this?

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92

4 Answers4

2

Because it is treated as bit field, you can use it in the same fashion.

FlagsAttribute Class

Indicates that an enumeration can be treated as a bit field; that is, a set of flags

bool result = (selected & compare) > 0; // First solution
bool result2 = (selected & compare).Any(); // Second solution
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
1

What you need is probably:

(selected & compare) > 0;
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
1

When you use an AND operator, any flag which is common between the two operands will be present in the result.

Then you just have to compare and see if the result is greater than Zero:

bool anySelected = (selected & compare) > 0;
Alireza
  • 4,976
  • 1
  • 23
  • 36
1

I think first you should remove the NULL from the Alpha, then just return (selected & compare) != 0, anyEnum.HasFlag(Alpha.NULL) will always be ture.

Norgerman
  • 79
  • 5