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

c#, coding-style

Solution

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

Problem

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.

Original source