Conditional operator without return value

本小妞迷上赌 提交于 2020-11-29 03:37:07

问题


I have this code:

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

and I want to shorten it by using the conditional operator but I can't find the correct syntax.

bool value = false;
value ? Console.Write("true") : Console.Write("false"); // does not work

回答1:


Put the operator inside Console.Write

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

or if you really want to write the value:

Console.Write(value);

if you want to call 2 different Methods, you can write your if-statement in one line:

if (value) Method1(); else Method2();



回答2:


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

If method returns a value then

bool value = false;
var result = value ? Test1() : Test2();

  private int Test1()
    {
        return 1;
    }

    private int Test2()
    {
        return 1;
    }



回答3:


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.



来源:https://stackoverflow.com/questions/38476719/conditional-operator-without-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!