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 :
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.
Only if, for example, they expose a fluent API and have a return value (i.e. something that allows you to squeeze multiple steps into a single expression); for example:
sb = (someCondition) ? sb.Append("foo").Append("bar")
: sb.Apppend("cde").Append("fgh");
otherwise? no; you only get a single expression to evaluate per case. You could refactor out to methods, of course;
var x = (someCondition) ? MethodA() : MethodB();
which again assumes a return value.
Create a function or delegate that accepts a number of arguments corresponding to the number of expressions you want to evaluate:
int i = 7, j = 8;
Func<int, int, int> dummy = ((a,b) => b);
int k = (i < 5) ? dummy(i++, j--) : dummy(i--, j++);
Console.WriteLine("{0}, {1}, {2}", i, j, k);
精彩评论