views:

277

answers:

3

Hi ::- ). Assume you have two integers, a = 8, b = 2. In C++ a | b is true. I used that behavior to work with collections of flags. For example the flags would be 1, 2, 4, 8 and so on, and any collection of them would be unique. I can't find how to do that in C#, as the | and & operators don't behave like they would in C++. I read documentation about operators in C# but I still don't get it.

EDIT:

Unfortunately, I seem to mess things up somewhere. Take this code for example:

byte flagCollection = 8;
byte flag = 3;

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

This returns "y" for whatever value I put in flag. Which is obvious, because 3 | 8 would be 11. Hmmmm... what I want to do is have a flag collection: 1, 2, 4, 8, 16 and when I give a number, to be able to determine what flags is it.

+8  A: 

It's not the bitwise and/or operators that are different in C#. They work almost the same as in C++. The difference is that in C# there isn't an implicit conversion from integer to a boolean.

To fix your problem you just need to compare to zero:

if ((a | b) != 0) {
   ...
Mark Byers
+12  A: 

The & and | operators in C# are the same as in C/C++. For instance, 2 | 8 is 10 and 2 & 8 is 0.

The difference is that an int is not automatically treated like a boolean value. int and bool are distinct types in C#. You need to compare an int to another int to get a bool.

if (2 & 8) ...         //  doesn't work

if ((2 & 8) != 0) ...  //  works
dtb
Any1 have an example use for this?
Paul Creasey
`int` isn't converted `to `bool` in C++ either, per se, since there is no `bool` type - `int`s are used as `bool`s.
Noldorin
@Noldorin:Not so -- C (before C99) didn't have a bool type, and at one time (well before standardization) C++ didn't either, but C has had bool (technically it's named _Bool) for about a decade, and C++ has had it even longer.
Jerry Coffin
@Noldorin: I don't know where you got that. In C++ there is a `bool` type. And every time you use anything in conditional context it is always converted to `bool` type first.
AndreyT
jalf
+5  A: 

Unlike C/C++, C# maintains a pretty strict separation between arithmetic and boolean operations.

The designers of C# considered the automatic conversion of integral types to boolean to be a source of errors that they'd rather C# didn't have, so you have to explicitly make your arithmetic results to a boolean result by introducing a comparison:

if ((a | b) != 0) {
    // ...
}

I think it's probably not a bad idea to do this in C/C++ as well, but I'll admit that I certainly don't strictly follow that advice (and I wouldn't argue for it very hard).

Michael Burr