Why are there no ||= or &&= operators in C#?

C#OperatorsLanguage DesignAssignment OperatorCompound Assignment

C# Problem Overview


We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators.

Why did the logical operators get left out? Is there a good technical reason why it is hard?

C# Solutions


Solution 1 - C#

> Why did the logical operators get left out? Is there a good technical reason why it is hard?

They didn't. You can do &= or |= or ^= if you want.

bool b1 = false;
bool b2 = true;
b1 |= b2; // means b1 = b1 | b2

The || and && operators do not have a compound form because frankly, they're a bit silly. Under what circumstances would you want to say

b1 ||= b2;
b1 &&= b2;

such that the right hand side is not evaluated if the left hand side does not change? It seems like only a few people would actually use this feature, so why put it in?

For more information about the compound operators, see my serious article here:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-one

and the follow-up April-Fools article here:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two

Solution 2 - C#

maybe just use

isAdmin = isAdmin || IsGroupAdmin()

I guess it is partially because a ||= b is kind of confusing because there might be two versions of the implementation: a = a || b, or a = b || a. And they act differently because the right-hand side of the expression is sometimes not evaluated.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge DuckettView Question on Stackoverflow
Solution 1 - C#Eric LippertView Answer on Stackoverflow
Solution 2 - C#温靖寰View Answer on Stackoverflow