Conditional operator without return value

前端 未结 3 1886
青春惊慌失措
青春惊慌失措 2021-01-16 07:15

I have this code:

bool value = false;
if(value)
{
    Console.Write(\"true\");
}
else
{
    Console.Write(\"false\");
}

and I want to short

3条回答
  •  迷失自我
    2021-01-16 07:55

    Just adding some precisions to the previous answer. The reason why you can't do this:

    value ? Console.Write("true") : Console.Write("false");
    

    Is because:

    The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

    source: MSDN

    The keyword here is "return". The ternary operator doesn't exactly replace an if/else statement, it is meant for assignment. You can of course call a method within a ternary operation as long as it returns a boolean value. A ternary operator must return something.

提交回复
热议问题