How to check if a flag is set in a flag enumeration?

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

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

and

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

<h / "> Please vote for the method you prefer.

+6
c # coding-style
source share
6 answers

Two expressions do different things (if fooFlag has more than one bit set), so it best 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 
+9
source share
 bool CheckFlag(FooFlag fooFlag) { return fooFlag == (this.Foo & fooFlag); } 
+6
source share

I prefer the first because it is more readable.

+3
source share
 bool CheckFlag(FooFlag fooFlag) { return (this.Foo & fooFlag) != 0; } 
+2
source share

I prefer the first one. I use! = 0 sparingly in boolean expressions.

+1
source share

I am a positive thinker:

 bool CheckFlag(FooFlag fooFlag) { return this.Foo & fooFlag == 1; } 
-2
source share

All Articles