Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 717
Andrew Harry Avatar asked Dec 04 '25 08:12

Andrew Harry


1 Answers

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

like image 164
vcsjones Avatar answered Dec 06 '25 00:12

vcsjones



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!