6

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 :

1
  • 1
    This is one instance of trying to use something unnecessarily just because it's cool. Commented Mar 14, 2011 at 12:20

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.