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条回答
别忘想泡老子
2楼-- · 2020-05-01 07:32

Please try the following. BTW, it only works for value assignments not method calls.

i = isOn ? 10 : 20;

Reference:

查看更多
干净又极端
3楼-- · 2020-05-01 07:35

You're on the right track but a little off. i = isOn ? 10 : 20;

Here 10 will be assigned to i if isOn == true and 20 will be assigned to i if isOn == false

查看更多
走好不送
4楼-- · 2020-05-01 07:40

Try the following:

i = isOn ? 10 : 20
查看更多
孤傲高冷的网名
5楼-- · 2020-05-01 07:42

try the following

i = isOn ? 10 :20
查看更多
Deceive 欺骗
6楼-- · 2020-05-01 07:43

You may simply try this:

i = isOn? 10:20

The MSDN says:

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

EDIT:-

If you want to invoke void methods in a conditional operator, you can use delegates else it is not possible to use ternary operators for methods.

And if your methods are returning something then try like this:

i = isOn ? foo() : bar();    //assuming both methods return int
查看更多
唯我独甜
7楼-- · 2020-05-01 07:45

You need:

i = true ? 10 : 20;

where true is your condition.

查看更多
登录 后发表回答