Bitwise connection two, if in one

I have it

public enum Condition : uint // bitwise { None = 0, NewLine = 1, Space = 2 } Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine; 

I would like to convert this,

 if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true; if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true; 

In something like

 if((someCondition & condition) == someCondition) return true; 

But it does not work. What am I forgetting?

+4
source share
3 answers

Well, if you just want to test nobody, then check > 0 . But if you are looking for a less specific solution, something like this will combine the two and generally remove the if :

 return (int)(someCondition & (Condition.Space | Condition.NewLine)) > 0 
+6
source

HasFlag specially developed for .NET 4 in .NET4:

 if (condition.HasFlag(someCondition)) return true; 

Here's the docs:

+3
source

someCondition has two bits, one for Rule.Condition.Space and one for Rule.Condition.NewLine . someCondition & condition will have one bit if the condition is Space or NewLine, otherwise 0 .

You should check if the bitwise operation returns 0 instead of checking for equality with someCondition

 if ((someCondition & condition) != 0) return true 
+2
source

All Articles