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?