I was playing around with using an lvalue as a result of conditional operator (cond ? expr1 : expr2
).
Consider following example
class /*(1)*/ Value {
public int MagicNumber { get; private set; } = 0;
public void Increment() {
/* magical code, that modifies MagicNumber */
}
}
void Main()
{
Value v1, v2;
/*(2)*/ bool condition = /*...*/;
(condition ? v1 : v2).Increment(); // (3)
}
Now, I would suspect, based on value of condition
, that either v1
or v2
gets incremented. That actually is the case, as long as Value
((1)
) is class. Once I change it to struct
, it becomes Value type and line (3)
does nothing (I would suspect because either v1
or v2
is copied, incremented and discarded). Up to this, it makes sense. The weird behavior begins once (2)
(condition
) is known at compile time (for example by defining it const bool
). Then some optimalization comes to play and one of v1
or v2
is actually incremented in place.
My question is, what should be the correct behavior of conditional operator in following case
(condition ? v1 : v2).Increment();
once v1
and v2
is struct
. Should it really depend on condition
being compile-time constant?
As suggested, I've sent bug report to the Microsoft and it turned out, that standard does not explicitly says whether result of conditional operator is r-value (value) or l-value (variable). By transitivity of other things in the standard, it seems, that result should be an r-value.
It was decided that the bug should be fixed and the fix is already on it's way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With