Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary/null coalescing operator and assignment expression on the right-hand side?

While experimenting with ternary and null coalesce operators in C# I discovered that it is possible to use assignments on the right-hand side of expressions, for example this is a valid C# code:

int? a = null;
int? b = null;
int? c = a ?? (b = 12);
int? d = a == 12 ? a : (b = 15);

Strangely enough, not only the assignment on the right-hand side of the expression is evaluated to its own right-hand side (meaning that the third line here is evaluated to 12 and not to something like b = 12 => void), but this assignment also effectively works, so that two variables are assigned in one statement. One can also use any computable expression on the right-hand side of this assignment, with any available variable.

This behaviour seems to me to be very strange. I remember having troubles with if (a = 2) instead of if (a == 2) comparison in C++, which is always evaluated to true and this is a common mistake after switching from Basic/Haskell to C++.

Is it a documented feature? Is there any name for it?

like image 542
Alexander Galkin Avatar asked Dec 22 '22 05:12

Alexander Galkin


1 Answers

This happens as consequence of the assignment operator also returning the value:

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result.

The expression b = 12 not only assigns 12 to b, but also returns this value.

like image 124
Oded Avatar answered Jan 14 '23 13:01

Oded