Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I check if a flag is set in a flags enum? [closed]

Of the two methods below, which do you prefer to read?
Is there another (better?) way to check if a flag is set?

 bool CheckFlag(FooFlag fooFlag)
 {
      return fooFlag == (this.Foo & fooFlag);
 }

And

 bool CheckFlag(FooFlag fooFlag)
 {
      return (this.Foo & fooFlag) != 0;
 }


Please vote up the method you prefer.
like image 494
Nescio Avatar asked Oct 15 '08 13:10

Nescio


People also ask

What are flags in enum?

A Flags is an attribute that allows us to represent an enum as a collection of values ​​rather than a single value. So, let's see how we can implement the Flags attribute on enumeration: [Flags] public enum UserType. {

What is Flag in VB net?

In general, "Flag" is just another term for a true/false condition. It may have more specific meanings in more specific contexts. For instance, a CPU may keep "arithmetic flags", each one indicating a true/false condition resulting from the previous arithmetic operation.

How do you use bit flags?

This is done by using the bitwise and shift operators to set, clear, and check individual bits in an integer, treating each bit as a separate boolean value. These individual bits are called bit flags. When talking about individual bits, we typically count from right to left, starting with leading “0” (zero).


4 Answers

The two expressions do different things (if fooFlag has more than one bit set), so which one is better really depends on the behavior you want:

fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set


(this.Foo & fooFlag) != 0       // result is true if any bits in fooFlag are set
like image 164
Michael Burr Avatar answered Oct 21 '22 05:10

Michael Burr


bool CheckFlag(FooFlag fooFlag)
{
    return fooFlag == (this.Foo & fooFlag);
}
like image 41
Sam Avatar answered Oct 21 '22 03:10

Sam


i prefer the first one because it's more readable.

like image 40
Enrico Murru Avatar answered Oct 21 '22 03:10

Enrico Murru


bool CheckFlag(FooFlag fooFlag)
{
    return (this.Foo & fooFlag) != 0;
}
like image 33
Chris Marasti-Georg Avatar answered Oct 21 '22 05:10

Chris Marasti-Georg