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 :
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With