Do nothing when “other side” of ternary operator is reached?

后端 未结 5 1759
醉酒成梦
醉酒成梦 2021-01-12 01:43

Note: I\'ve seen this question asked sometimes before (a, b, c), but neither of these was in C#, nor helpful.

Assume I\'m using the ? : ternary

5条回答
  •  北海茫月
    2021-01-12 02:19

    The other answers are correct, but they miss out a key point which I think is the main thing you're having an issue with. The thing to notice is that

    r = 0

    apart from assigning r a value, returns the same value too. You can think of it like a function. You can call a function, which maybe does some other stuff apart from returning a value, which you may or may not put into use.

    Take for example:

    int square(int n)
    {
        // Now you can do other things here too. Maybe you do something with the UI in here:
        Console.WriteLine("Calculating...");
        // ^ Now thing of the above code as assigning a value to a variable.
        return n * n;
        // But after assigning the value, it also returns the value...
    }
    

    So, now suppose you may have two usage cases:

    var x = square(2);
    // -- OR --
    square(2);
    

    Note that both statements output 'Calculating...' but the former assigns a value of 2 * 2 or 4 to x.

    Even better, let's say we have a function:

    int AssignValueToVariable(out int variable, int value)
    {
        variable = value;
        return value;
    }
    

    Now the function is obviously redundant, but let's suppose we can use it for better understanding. Assume that it is equivalent to the assignment = operator.

    That said, we can come back to our scenario. The ternary operator ? : takes in two expressions to return on the basis of a specified condition. So, when you write:

    r == 5 ? r = 0 : r = 2; // Let's suppose the third operand to be r = 2
    

    it is equivalent to:

    r == 5 ? AssignValueToVariable(r, 0) : AssignValueToVariable(r, 2)
    

    both of which are essentially:

    r == 5 ? 0 : 2
    

    That brings back the hard and fast rule that the operands must be expressions as the entire thing must boil down to an expression. So, you can get a kind of 'nothing' equivalent for an expression by using its default value.

    Or, as the other answers mention, use an if statement, straight and simple:

    if (r == 5)
        r = 0;
    

    Extrapolating from the code you provided, I'd guess you're doing something with the evaluated expression. You can store the value in a separate variable result and do whatever with it:

    int result;
    if (r == 5)
        result = r = 0; // This sets the value of both result and r to 0
    

    Now, you can substitute result for your previous expression you wanted, i.e., r == 5 ? r = 0 : // Pseudo-code.

    Hope it helps :)

提交回复
热议问题