4

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?

Chuck Savage
  • 11,274
  • 6
  • 46
  • 65
  • I am not quite understand what you want. You can use Flag attribute to make sure life easier when there is a bitwise related conditions. Here is a good source for Flag Attribute http://stackoverflow.com/questions/8447/enum-flags-attribute – CharithJ May 17 '11 at 03:23
  • It is more complex than what I posted. But if the 'previous' to the current check is a space or new line, then true. Otherwise I have to check other things. – Chuck Savage May 17 '11 at 03:28

3 Answers3

6

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
drharris
  • 10,958
  • 5
  • 40
  • 55
  • Ok, thanks - I check for other things, so I need the if - thanks to you and sverre for getting back so quickly. – Chuck Savage May 17 '11 at 03:27
  • Gotcha. If you are using a similar test multiple times, you probably should do something like `var test = Condition.Space | Condition.NewLine`, then you can reuse it as `if ((someCondition & test) > 0)` wherever you need it. Also, consider using the `[Flags]` attribute on your enum, as it provides some built-in functionality for you. – drharris May 17 '11 at 03:30
3

There is a special convenience method HasFlag in .NET4 expressly for this purpose:

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

Here's the docs:

Rick Sladkey
  • 32,829
  • 6
  • 69
  • 93
2

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
sverre
  • 6,402
  • 2
  • 25
  • 35