JaykeBird
JaykeBird

Reputation: 382

How does the or-assignment operator (|=) work? (C#)

I've seen documentation and answers (1) (2) that try to explain what the |= operator is and how it works, and while it kind of makes sense on a basic level... I don't quite get why or how it accomplishes what it does.

The explanations say that a |= b is equivalent to a = a | b, but I don't get how it evaluates whether to give a the value of itself (a) or the value of b. From my understanding, "or" means that it can be one of two things, but doesn't specify which of the two things it is.

In Visual Studio, I use an extension called Refactoring Essentials, which suggested I replace some of my code with a line with the |= operator, and while the code works with the operator in there, I'm lost as to how it accomplishes it, which is what prompted me to try to research it online (and as a result, ask this question).

My code went from

if (MessageBox.Show("Are you sure you want to cancel this operation?", "Confirm Cancel", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.No)
{
    e.Cancel = true;
}

to

e.Cancel |= MessageBox.Show("Are you sure you want to cancel this operation?", "Confirm Cancel", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.No) == MessageBoxResult.No;

and it still worked. While I would guess that e.Cancel is determined based upon the evaluation of MessageBox.Show(...) == MessageBoxResult.No, I don't know why the |= operator is needed there. Why not just use a standard assignment (=) operator, as the result of the expression is a boolean and e.Cancel takes a boolean? And what about using the conditional (? :) operator? How does |= compare to that (if it even does)?

Upvotes: 0

Views: 2847

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109547

| is the BITWISE OR operator, it is not a BOOLEAN OR operator.

Suppose you have two 8-bit binary numbers 10110100 and 11000101.

If you bitwise OR them you will get a 1 bit set in the output for each position where a bit is set in the first OR the second input, and a 0 bit where NEITHER of the two input bits are set:

10110100 
11000101
--------
11110101

That's all there is to it.

As you already know, x |= y; is exactly the same as x = x | y;.

The final point to note is that bool is treated as if it were a one-bit number where 1 = true and 0 = false, for the purposes of | and & bitwise operations when applied to bool.

However, do note that you cannot mix bool and int bitwise operations. For example, the following will give a compile error:

bool t = true;
bool f = false;
int x = t | f; // Error: Cannot implicitly convert type 'bool' to 'int'

ADDENDUM:

The reason that people use &= and |= for bool rather than what would seem the more logical (pun intended) &&= and ||= is that the latter two operators don't actually exist!

Upvotes: 7

Related Questions