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;
}
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. {
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.
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).
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
bool CheckFlag(FooFlag fooFlag)
{
return fooFlag == (this.Foo & fooFlag);
}
i prefer the first one because it's more readable.
bool CheckFlag(FooFlag fooFlag)
{
return (this.Foo & fooFlag) != 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With