-1

I want to convert this if, else-if, can someone help me out please?

if (condition1)
    response.Redirect(" some link");
else if (condition2)
    response.Redirect("link 2");

I want convert above statement,but showing error at the end, required ":". Any other way i can use this?

LinkPurchase.PostBackUrl =((Condition)?string.Format("some link"):  
                        (condition2)?string.Format("link 2));

2 Answers2

0

You cannot rewrite that to the ?: operator.

You have an if-else if, not just an if-else.

Besides, you do not pick up the return values from the Redirect calls.

The usual case where you do want to rewrite to the ?: operator is:

if (condition)
  something = Abc();
else
  something = Xyz();

where it is natural to use instead:

something = condition ? Abc() : Xyz();
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • He *could*. It almost certainly wouldn't be a good idea, but it's absolutely possible. – Servy Jul 31 '14 at 15:07
  • @Servy I wonder how? Are you going to answer something like `(condition1 ? () => response.Redirect(" some link") : condition2 ? () => response.Redirect("link 2") : (Action)(() => { }))();` (I made it!)? – Jeppe Stig Nielsen Jul 31 '14 at 15:23
  • That's certainly one way, yes. Not the only way of course, but you've now successfully proved your own answer wrong. – Servy Jul 31 '14 at 15:24
  • @Servy Nothing can prove a perfect answer wrong, not even the comments of its own author. – Jeppe Stig Nielsen Jul 31 '14 at 15:31
  • I'll be sure to test that theory out when I actually find a perfect answer. – Servy Jul 31 '14 at 15:33
0

You cannot do this.

There are other answers here that inform you that the ?: operator needs the "else" part, so yes, the first problem is that you're missing that.

However, Response.Redirect doesn't return anything, so you cannot do this even with the else part.

?: is an expression, you cannot write statements (easily) with this.

Stick with the if-statements.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825