Ternary with boolean condition in c#

2020-05-01 07:16发布

If I am to write this piece of code, it works fine with the normal 'if-else' layout.

if(isOn)
{
    i = 10;
}
else
{
    i = 20;
}

Although I am unsure how to convert this using the ternary operator

        isOn = true ? i = 1 : i = 0;

Error: Type of conditional expression cannot be determined because there is no implicitly conversion between 'void' and 'void'.

EDIT: Answer = i = isOn ? 10 : 20;

Is it possible to do this with methods?

if(isOn)
{
    foo();
}
else
{
    bar();
}

7条回答
Ridiculous、
2楼-- · 2020-05-01 07:47

Here's an explanation that might help. The statement you're looking for is:

i = isOn ? 10 : 20;

And here's what that means:

(result) = (test) ? (value if test is true) : (value if test is false);
查看更多
登录 后发表回答