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

后端 未结 5 1806
醉酒成梦
醉酒成梦 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:16

    You can't. The whole point of the conditional ?: operator is that it evaluates an expression. You can't even just use:

    Foo() ? Bar() : Baz();
    

    ... because that isn't a statement. You have to do something with the result... just like when you access a property, for example.

    If you want to only execute a piece of code when a specific condition is met, the ?: operator isn't what you want - you want an if statement:

    if (foo)
    {
        bar();
    }
    

    It's as simple as that. Don't try to twist the conditional operator into something it's not meant to be.

提交回复
热议问题