TruMan1
TruMan1

Reputation: 36078

Is there an "and assignment operator" for && and || for shorthand?

To add a value and assign it back to itself, I would do this:

x = x + y;

For making that shorthand, I can use the add assignment operator like this:

x += y;

Is there a shorthand like this for the && and || operator for this?:

x = x && y;

I tried the below, the results is not the same as above:

x &= y;

Upvotes: 3

Views: 756

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

No, there is not as it doesn't make too much sense.

According to MSDN, there are only the following shortand operators in C#:

x += y – increment
x -= y – decrement    
x *= y – multiplication assignment
x /= y – division assignment
x %= y – modulus assignment
x &= y – AND assignment
x |= y – OR assignment
x ^= y – XOR assignment
x <<= y – left-shift assignment
x >>= y – right-shift assignment

Upvotes: 1

WBT
WBT

Reputation: 2465

You can see the list of C# operators here.

x &= y – AND assignment. AND the value of y with the value of x, store the result in x, and return the new value.

x |= y – OR assignment. OR the value of y with the value of x, store the result in x, and return the new value.

When you say "the results is not the same," can you provide example values of x and y that you're testing?
I think what you're observing is the difference between logical/bitwise AND/OR (&/|) and conditional AND/OR (&&/||). The latter will not evaluate y if it doesn't need to in order to figure out the value of the expression. If the evaluation of y has side effects, you would notice a difference between the bitwise and conditional operators.

Upvotes: 2

Related Questions