Andrew Harry
Andrew Harry

Reputation: 13909

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

Upvotes: 3

Views: 306

Answers (3)

vcsjones
vcsjones

Reputation: 141638

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

Upvotes: 8

user499054
user499054

Reputation:

It's a bitwise OR operator, not to be confused with logical or (dealing with bools).

Wikipedia has a great article on this: http://en.wikipedia.org/wiki/Bitwise_operation#OR

Upvotes: 0

Josh
Josh

Reputation: 69262

For your reference - C# Operators and |=

Upvotes: 3

Related Questions