Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Difference betwen passing multiple enum values with pipe and ampersand

C# accepts this:

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

and this:

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

Whats the difference?

like image 545
Diego Avatar asked Nov 09 '10 12:11

Diego


2 Answers

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");
like image 131
Pieter van Ginkel Avatar answered Oct 03 '22 00:10

Pieter van Ginkel


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.

like image 30
SwDevMan81 Avatar answered Oct 02 '22 23:10

SwDevMan81