Alexander Galkin
Alexander Galkin

Reputation: 12554

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?

Upvotes: 4

Views: 1671

Answers (2)

Oded
Oded

Reputation: 499262

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.

Upvotes: 10

Andrew Barber
Andrew Barber

Reputation: 40160

Multiple assignment works 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 an equation, even if it has just been assigned a value itself on the same line, it returns its value/reference.

Upvotes: 1

Related Questions