Reputation: 11945
I have this,
public enum Condition : uint // bitwise
{
None = 0,
NewLine = 1,
Space = 2
}
Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;
I'd like to convert this,
if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;
Into something like,
if((someCondition & condition) == someCondition) return true;
But it isn't working. What am I forgetting?
Upvotes: 4
Views: 263
Reputation: 34240
There is a special convenience method HasFlag
in .NET4 expressly for this purpose:
if (condition.HasFlag(someCondition)) return true;
Here's the docs:
Upvotes: 3
Reputation: 6919
someCondition
has two bits set, one for Rule.Condition.Space
and one for Rule.Condition.NewLine
. someCondition & condition
will have one bit set if condition
is Space or NewLine, and be 0
otherwise.
You should test if the bitwise operation returns 0
instead of checking for equality with someCondition
if ((someCondition & condition) != 0) return true
Upvotes: 2
Reputation: 11214
Well, if you're just wanting to test for none, then check for > 0
. But, if you're looking for a less specific solution, something like this would combine the two and remove the if
altogether:
return (int)(someCondition & (Condition.Space | Condition.NewLine)) > 0
Upvotes: 6