Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

& operator with enum values in C#

Tags:

c#

enums

I have following code and Console.WriteLine is returning Bottom even though Bottom is not in both enum expressions.

Question

What is the logic behind returning Bottom in code snippet given below? My understanding of & operator is that it returns the common part, but in this case there is nothing common between the two enum expressions.

void Main()
{
    Console.WriteLine(( Orientations.Left | Orientations.Bottom) & 
                     (Orientations.Right| Orientations.Top));//returns Bottom
}


[Flags]
public enum Orientations {
Left = 0, Right= 1, Top=2, Bottom =3
};
like image 347
Sunil Avatar asked Jan 29 '26 03:01

Sunil


1 Answers

You assign values to the enums, and the operators | and & work on the enum values, like they would work on the corresponding values.

You have set the values of the enum values yourself, and you have not set them orthogonal. Since integers are in fact bitstrings (with fixed length), you can see it as a 32-dimensional vector (with every vector element having domain {0,1}). Since you defined for instance Bottom as 3, it means that Bottom is actually equal to Right | Top, since:

Right | Top
    1 |   2  (integer value)
   01 |  10  (bitwise representation)
   11        (taking the bitwise or)
Bottom

So that means that if you write &, this is a bitwise AND, and |, is a bitwise OR on the values of the enum values.

So if we now evaluate it, we get:

(Orientations.Left|Orientations.Bottom) & (Orientations.Right|Orientations.Top)
(0                | 3                 ) & (1                 | 2)
3                                       & 3
3
Orientations.Bottom

If you want to define four orthogonal values, you need to use powers of two:

[Flags]
public enum Orientations {
    Left = 1,    // 0001
    Right = 2,   // 0010
    Top = 4,     // 0100
    Bottom = 8   // 1000
};

Now you can see the enum as four different flags, and and the & will create the intersection, and | the union of the flags. In comment the bitwise representation of each value is written.

As you can see, we can now see Left, Right, Top and Bottom as independent elements, since we can not find a monotonic bitwise construction ( to combine Left, Right and Top to construct Bottom (except negation).

like image 52
Willem Van Onsem Avatar answered Jan 31 '26 16:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!