tags:

views:

87

answers:

3

Hi everybody. I've been trying to emulate in C# a behavior which I was implementing without any problems in C++. I have a flag collection, which based on powers of 2, and a flag which I need to check if it exists in the collection.

  byte flagCollection = 1 | 2 | 4 | 8;
  byte flag = 2;

  if ((flagCollection & flag) != 0) MessageBox.Show("y"); else MessageBox.Show("n");

Now, the problem is that whatever I set Flag to (2, 3, 100, 211), I always get "y", except for 0. Of course, 1, 2, 4, 8 would be some constants which have various meanings in my application.

In C++:

if (flagCollection & flag)

Would result in TRUE for the variables above.

+1  A: 

well, if you're flag collection has OR'd 1,2,4,8, uh yes I think every positive integer that's not a multiple of 16 when &'d to it is going to return something. Or am I missing something?

charoco
C# behavior confused me. It acts a bit different that C++. What I wanted to do is to check if a certain flag OR COMBINATION of flags is within the collection.
Axonn
+2  A: 

The way you are doing it seems correct. I'm not really sure what behavior you are expecting. Any of the flags you listed (2, 3, 100, 211) do contain an element of 1 | 2 | 4 | 8. If you want to check whether all of them are present you should be doing

if ((flagCollection & flag) == flag) 
   // ...
Andrey
Thank you, that's what I wanted to do actually.
Axonn
Axonn
Nope, in C++ you'd have to do the same.
dtb
A: 

Would this work?

[Flag]
public enum flagCollection {
  Type1,
  Type2,
  Type4,
  Type8,
}

flagCollection testValue = flagCollection.Type2

if ((testValue & flagCollection.Type2) == flagCollection.Type2) {
   MessageBox.Show("y");
} else {
   MessageBox.Show("n");
}

Not in front of the compiler so cant chek if that will work or not.

GrayWizardx
Yeah, that works, except it's "Flags" not "Flag", the compiler complained about it in the "if" instruction. Didn't know about that attribute. Thank you! ::- ).
Axonn
You also need to assign values explicitly to the enum elements, because even if you decorate the enum with `Flags` the values assigned automatically are still 0, 1, 2, 3, 4, ...
dtb
*laugh* that's weird. I imagined that's EXACTLY why the Flags attribute is there. If it doesn't do that, then why use it in the first place? Strange. I looked in MSDN and they only say "Indicates that an enumeration can be treated as a bit field; that is, a set of flags.". Ok, now that they told me that, I can sleep well *laugh*.
Axonn
I thought Flags automatically did binary shifting on a value. LOL! Learn omething new ever day.
GrayWizardx