). 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.
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
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) {
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With