C# Ternary Operator – Using Ternary with Boolean Condition in C#

c++ternary-operator

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();
}

Best Answer

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

i = isOn ? 10 : 20;

Reference:

Related Question