[ACCEPTED]-C# Difference betwen passing multiple enum values with pipe and ampersand-parameter-passing

Accepted answer
Score: 23

When you do |, you select both. When you do &, you only what overlaps.

Please note that these operators only make 9 sense when you apply the [Flags] attribute to your 8 enum. See http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx for a complete explanation on 7 this attribute.

As an example, the following 6 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 5 testValue overlaps with Value1And2 (i.e. is part of):

if ((testValue & TestEnum.Value1And2) != 0)
    Console.WriteLine("testValue is part of Value1And2");

Here we 4 test whether testValue is exactly equal to Value1And2. This 3 is of course not true:

if (testValue == TestEnum.Value1And2)
    Console.WriteLine("testValue is equal to Value1And2"); // Will not display!

Here we test whether 2 the combination of testValue and Value2 is exactly equal 1 to Value1And2:

if ((testValue | TestEnum.Value2) == TestEnum.Value1And2)
    Console.WriteLine("testValue | Value2 is equal to Value1And2");
Score: 9
this.MyMethod(enum.Value1 | enum.Value2);

This will bitwise 'OR' the two enum values 6 together, so if enum.Value is 1 and enum.Value2 is 2, the result 5 will be the enum value for 3 (if it exists, otherwise 4 it will just be integer 3).

this.MyMethod(enum.Value1 & enum.Value2);

This will bitwise 3 'AND' the two enum values together, so if 2 enum.Value is 1 and enum.Value2 is 3, the result will be the 1 enum value for 1.

Score: 6

One is bitwise-or, the other is bitwise-and. In 6 the former case this means that all the 5 bits that are set in one or the other are 4 set in the result. In the latter case this 3 means that all the bits that are in common 2 and set in both are set in the result. You 1 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
Score: 4

This question has a nice explanation: What does the [Flags] Enum Attribute mean in C#?

0

Score: 2

Enum parameters can be binary numbers, for 3 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 2 & to strip some part of the value, for 1 example

if (ws & WorldSides.North)
{
     //  ws has north component
}

More Related questions