Marc C
Marc C

Reputation: 329

Ternary with boolean condition in c#

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

Upvotes: 1

Views: 27176

Answers (7)

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

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

Upvotes: 5

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

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

i = isOn ? 10 : 20;

Reference:

Upvotes: 14

MikeH
MikeH

Reputation: 4395

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

Upvotes: 4

Rick Liddle
Rick Liddle

Reputation: 2714

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

Upvotes: 3

Dennis Traub
Dennis Traub

Reputation: 51634

Try the following:

i = isOn ? 10 : 20

Upvotes: 2

user2711965
user2711965

Reputation: 1825

You need:

i = true ? 10 : 20;

where true is your condition.

Upvotes: -3

Tilak
Tilak

Reputation: 30698

try the following

i = isOn ? 10 :20

Upvotes: 2

Related Questions