views:

270

answers:

6

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.

+3  A: 

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

Enreeco
+1  A: 

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

Dana
+5  A: 
bool CheckFlag(FooFlag fooFlag)
{
    return fooFlag == (this.Foo & fooFlag);
}
Chris Marasti-Georg
+2  A: 
bool CheckFlag(FooFlag fooFlag)
{
    return (this.Foo & fooFlag) != 0;
}
Chris Marasti-Georg
A: 

I'm a positive thinker:

bool CheckFlag(FooFlag fooFlag)
{
  return this.Foo & fooFlag == 1;
}
Phil Reif
What if FooFlag's value is 2?
Chris Marasti-Georg
He said he is a positive thinker :)
leppie
I stand corrected - thinking before writing is helpful ;)
Phil Reif
+8  A: 

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
Michael Burr
Thanks! I guess I was only looking at it one way. ie, "Is my bit set" I guess it could be helpful to know if "Any" bit is set as well!
Nescio