Search code examples
c#c#-4.0language-features

What does the |= operator do in C#?


Browsing the code sample from C# 4.0 in a nutshell I came across some interesting operators involving enums

[Flags]
public enum BorderSides { Left=1, Right=2, Top=4, Bottom=8 }

...
BorderSides leftRight = BorderSides.Left | BorderSides.Right;
...

BorderSides s = BorderSides.Left;
s |= BorderSides.Right;
...

s ^= BorderSides.Right; 

Where is this documented somewhere else?

UPDATE

Found a forum post relating to this


Solution

  • |= is a bitwise-or assignment.

    This statement:

    BorderSides s = BorderSides.Left;
    s |= BorderSides.Right;
    

    is the same as

    BorderSides s = BorderSides.Left;
    s = s | BorderSides.Right;
    

    This is typically used in enumerations as flags to be able to store multiple values in a single value, such as a 32-bit integer (the default size of an enum in C#).

    It is similar to the += operator, but instead of doing addition you are doing a bitwise-or.