In an example I saw these operators (|= and &=) but it wasn't explained. I was looking on Google about it, but I found only results related to the "classic" = operator.
So I would like to know what are these operators doing. Can somebody explain it to me ?
4 Answers
They are simply shorthand assignments like +=. The following are equivalent:
s |= t; s = s | t; And these are also equivalent.
s &= t; s = s & t; For more information on those operators, you can see the MSDN Docs on | and & Operator.
5 Comments
josefpospisil0
Wow ! That was fast ! Thank you for the explain and the links ;-) Sorry for this noob question.
Servy
They aren't strictly equivalent. The
|= operator will ensure that the left hand side is only evaluated once, not twice. It's still an appropriate way to conceptualize it, even though they're not exactly the same.mellamokb
@Servy: Thanks for pointing that out. Aren't they still functionally equivalent, even if the underlying OP-codes might translate slightly differently?
Servy
@mellamokb No, they're not. In your example
s might not just be a local variable. It could be an expression that results in side effects. The |= case those side effects only occur once, in the following example they would occur twice.mellamokb
@Servy: Gotcha. Though that's true with a lot of operations if you don't use good programming practices. I would consider side effects resulting from modifying a local variable/property a red flag.
|= and &= are assignment operators related to the | (bitwise or) and & (bitwise and) operators.
|=Operator (C# Reference)