Why can't I use break in a C# ternary expressi

2019-03-07 04:50发布

I am trying to convert the if else clause to a ternary within a while loop, however it's not allowing me to have a break after the question mark, pointing an error at the break as an invalid expression.

How would I go about turning this simple if else into a ternary like so.

while (true)
{
    Console.WriteLine("Enter 3 words seperated by spaces: ");
    var input = Console.ReadLine();
    //input == "" ? break : ConvertToPascal(input);
    if (input == "")
        break;
    else
        ConvertToPascal(input);
    }
}

2条回答
手持菜刀,她持情操
2楼-- · 2019-03-07 05:23

Because the ternary is not a shorter way to write an if-else structure, it's a short way to write an expression that picks one of two values based on some condition. break is a flow-control statement, not a value.

If it helps, think of:

someVar = cond ? a : b;

as of:

someVar = getValue(cond);
查看更多
趁早两清
3楼-- · 2019-03-07 05:36

It isn't possible using the ternary operator, but you can simplify your code structure as follows:

string input;
do {
    Console.WriteLine("Enter 3 words seperated by spaces: ");
    input = Console.ReadLine();
    if (input != "") {
        ConvertToPascal(input);
    }
} while(input != "");
查看更多
登录 后发表回答