It might be an easy and simple question but I still have a little confusion the reason why bitwise OR is decided to use. Assume I have a class A with four fields:
class A
{
private int Field1;
private static int Field2;
public int Field3;
public static int Field4;
}
And use Reflection to get fields:
var fields = typeof (A).GetFields(BindingFlags.Public | BindingFlags.Static);
If you are newbie with Reflection and don’t know the way how to use BindingFlags, the initial logic thinking in your head would be:
This line will select all static OR public fields because bitwise OR is used. And the expected result you think:
Field2
Field3
Field4
But when hitting F5, the result will be totally different, bitwise OR works as AND:
Field4
Why not use bitwise AND operator which might follow with the logic thinking. like this:
var fields = typeof (A).GetFields(BindingFlags.Public & BindingFlags.Static);
I found words in MSDN:
the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks.
Please could anyone explain the advance concept in here in simple way for understanding?
See the end for a short summary.
Long answer:
Bitwise OR is combining the bits of the enum flags.
Example:
BindingFlags.Publichas the value of 16 or 10000 (binary)BindingFlags.Statichas the Value of 8 or 1000 (binary)bitwise OR combines these like the following:
bitwise AND would combine them like this:
That’s a very basic concept of Flags:
Each value is a power of two, e.g.:
2^02^12^22^3Their bit representation is always a
1and the rest zeros:Combining any of them using bitwise AND would always lead to 0 as there are no
1at the same position. Bitwise AND would lead to a complete information loss.Bitwise OR on the other hand will always result in an unambiguous result. For example, when you have (binary) 1010 (decimal 10) you know it originally has been 8 and 2. There is no other possibility 10 could have been created.
As Default said, the method you called can later extract this information using the bitwise AND operator:
The bitwise OR in this case is basically a vehicle to transport the values to the method you are calling.
What this method does with these values has nothing to do with the usage of bitwise OR.
It can internaly require ALL passed flags to match as is the case for
GetFields. But it also could require only one of the passed flags to match.For you as a caller, the following would be equivalent:
Now that doesn’t compile as
GetFieldsdoesn’t provide such an overload, but the meaning would be the same as that of your code.To sum things up (TL;DR):
Bitwise AND has nothing to do with Boolean AND
Bitwise OR has nothing to do with Boolean OR