Ternary / zero coalescence operator and assignment on the right side?

During experiments with triple and zero coalescing operators in C #, I found that you can use the assignments on the right side of the 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); 

Oddly enough, not only the assignment on the right side of the expression is evaluated on its own right side (this means that the third line here is evaluated as 12 , and not something like b = 12 => void ), but this assignment also works effectively. so two variables are assigned in one expression. You can also use any calculated expression on the right side of this assignment with any variable available.

This behavior seems very strange to me. I remember that I had problems with if (a = 2) instead of comparing if (a == 2) in C ++, which is always evaluated as true , and this is a common mistake after switching from Basic / Haskell to C ++.

Is this a documented feature? Is there a name for this?

+4
source share
2 answers

This happens as a result of the assignment operator also returning a value:

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

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

+10
source

Several tasks work in C #:

 int a; int b; int c; a = b = c = 5; //all variables = 5; if(6 == (c = 6)){ //this will be true; } 

If you put a variable on the right side of the equation, even if it has just been assigned a value in one line, it returns the value / reference.

+1
source

Source: https://habr.com/ru/post/1384700/


All Articles