Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i write multiple statement using conditional operator

I am writing conditional operator in place of if else . But i my case i have multiple statements as following

if (condition)
{
    statement 1;
    statement 2;
}
else
{
    statement 3;
    statement 4;
}

How could i write same using conditional operator ? and :

like image 434
Hemant Kothiyal Avatar asked Mar 14 '11 12:03

Hemant Kothiyal


2 Answers

The conditional operator is designed for evaluating alternative expressions, not invoking alternative statements.

If your two sets of statements each logically have the same result type, you could refactor to put each of them in a separate method:

var result = condition ? Method1() : Method2();

but if they're logically more to do with side-effects than evaluating a result, I would use an if block instead.

like image 117
Jon Skeet Avatar answered Nov 07 '22 13:11

Jon Skeet


You can't, because the conditional operator is an expression, not a statement. You have to use an if-else construct to achieve what you're trying to do.

like image 28
BoltClock Avatar answered Nov 07 '22 11:11

BoltClock