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.
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