简体   繁体   中英

What does the “|=” operator do in C#?

I've recently come across some code that I don't fully understand. Below is a basic representation of this code:

bool flag = false;
flag |= someFunction();

In this example, someFunction() is a function that returns a bool value. My question is, what does the | = operator do?

I haven't found much information regarding |= on the web or in this community. I understand basic assignment operations using the = operator, comparison operations using the = = operator or the other variants, but I've never seen |= used in an assignment before.

I also know that the | operator is used for a bitwise inclusive OR comparison. However, it doesn't make sense to me to use this as part of an assignment. In sudo code it seems that the code above is saying "If the result of a bitwise inclusive OR between "flag" and someFunction() results in a true value, assign the true value to flag. Otherwise, assign the value of false to flag." Of course, if either flag or someFunction() stored/returned a true value then the result would be true (based on how a bitwise inclusive OR works).

Is this a correct interpretation? If that is how |= works, since I know that "flag" is false does it really make any sense to use the |= operator as opposed to a simple = assignment operator in this scenario?

Thanks in advance.

You are correct that = would have the same effect in your case.

In general, if there are several such conditions, the first one may use |= simply for consistency, but it has no technical advantage here.

flag |= someFunction() is equivalent to flag = flag | someFunction(); flag = flag | someFunction();
This is the OR assignment operator.

Please see MSDN for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM