Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference semantics of conditional operator

Tags:

c#

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?

like image 860
Zereges Avatar asked Nov 09 '22 00:11

Zereges


1 Answers

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.

like image 157
Zereges Avatar answered Nov 14 '22 21:11

Zereges