C# accepts this:
this.MyMethod(enum.Value1 | enum.Value2);
and this:
this.MyMethod(enum.Value1 & enum.Value2);
Whats the difference?
C# accepts this:
this.MyMethod(enum.Value1 | enum.Value2);
and this:
this.MyMethod(enum.Value1 & enum.Value2);
Whats the difference?
When you do |
, you select both. When you do &
, you only what overlaps.
Please note that these operators only make sense when you apply the [Flags]
attribute to your enum. See http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx for a complete explanation on this attribute.
As an example, the following enum:
[Flags]
public enum TestEnum
{
Value1 = 1,
Value2 = 2,
Value1And2 = Value1 | Value2
}
And a few test cases:
var testValue = TestEnum.Value1;
Here we test that testValue
overlaps with Value1And2
(i.e. is part of):
if ((testValue & TestEnum.Value1And2) != 0)
Console.WriteLine("testValue is part of Value1And2");
Here we test whether testValue
is exactly equal to Value1And2
. This is of course not true:
if (testValue == TestEnum.Value1And2)
Console.WriteLine("testValue is equal to Value1And2"); // Will not display!
Here we test whether the combination of testValue
and Value2
is exactly equal to Value1And2
:
if ((testValue | TestEnum.Value2) == TestEnum.Value1And2)
Console.WriteLine("testValue | Value2 is equal to Value1And2");
this.MyMethod(enum.Value1 | enum.Value2);
This will bitwise 'OR' the two enum values together, so if enum.Value
is 1 and enum.Value2
is 2, the result will be the enum value for 3 (if it exists, otherwise it will just be integer 3).
this.MyMethod(enum.Value1 & enum.Value2);
This will bitwise 'AND' the two enum values together, so if enum.Value
is 1 and enum.Value2
is 3, the result will be the enum value for 1.
One is bitwise-or, the other is bitwise-and. In the former case this means that all the bits that are set in one or the other are set in the result. In the latter case this means that all the bits that are in common and set in both are set in the result. You can read about bitwise operators on Wikipedia.
Example:
enum.Value1 = 7 = 00000111
enum.Value2 = 13 = 00001101
then
enum.Value1 | enum.Value2 = 00000111
|00001101
= 00001111
= 15
and
enum.Value1 & enum.Value2 = 00000111
&00001101
= 00000101
= 5
This question has a nice explanation: What does the [Flags] Enum Attribute mean in C#?
Enum parameters can be binary numbers, for example
enum WorldSides
{
North=1,
West=2,
South=4,
East=8
}
WorldSides.North | WorldSides.West = both values -> 3
So, | is used to combine the values.
Use & to strip some part of the value, for example
if (ws & WorldSides.North)
{
// ws has north component
}