Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if more than one enum flag is set?

Tags:

c#

enums

I just want to know if exactly one enum flag is set, not which ones. My current thinking is to check if it is a power of 2. Is there a better way built into enum types?

[Flags]
enum Foo
{
Flag1 = 0x01,
Flag2 = 0x02,
Flag3 = 0x04,
Flag4 = 0x08,
Flag5 = 0x10,
Flag6 = 0x20,
Flag7 = 0x40,
Flag8 = 0x80
}

private bool ExactlynOneFlagSet(Foo myFoo)
{
  var x = (byte) myFoo;
  return (x != 0) && ((x & (x - 1)) == 0); //Check if a power of 2
}

if(!ExactlynOneFlagSet(Foo myFoo))
{
   //Do something
}
like image 289
mcintoda Avatar asked Jan 21 '12 00:01

mcintoda


People also ask

How do you know if a flag is set?

FLAG – Check if flag is set This function checks if binary flags are set within a byte, but performed in decimal number form, to avoid having to convert values to binary. The function returns 1 if the bits in <check> are also set in <source> . On the contrary, it returns 0.

What are enum flags?

The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

Do enums have to be sequential?

There is nothing that requires them to be sequential. Your enum definition is fine and will compile without issue.


3 Answers

Its a Bit operation!

if ((myFoo & (myFoo -1)) != 0) //has more than 1 flag

The statement checks if the value of myFoo is not power of two. Or, vice versa, the statement (myFoo & (myFoo -1)) == 0 checks for power of two. The idea is that only single flag values will be power of two. Setting more than one flag will result in a non power of two value of myFoo.

More information can be found in this answer to a similar question: https://stackoverflow.com/a/1662162/2404788.

For more information about bit operations go to http://en.wikipedia.org/wiki/Bitwise_operation

like image 75
Guido Zanon Avatar answered Oct 01 '22 05:10

Guido Zanon


If the enum doesn't define explicit combinations of flags, you can just check if the value is defined in the enum:

private bool ExactlynOneFlagSet(Foo myFoo)
{
    return Enum.IsDefined(typeof(Foo), myFoo);
}
like image 10
Thomas Levesque Avatar answered Oct 01 '22 04:10

Thomas Levesque


private bool ExatlyOneFlagSet(Foo myFoo)
{
  return !myFoo.ToString().Contains(',');
}
like image 8
itsme86 Avatar answered Oct 01 '22 04:10

itsme86