View Full Version : shorthand for else if?

07-02-2011, 04:12 PM

I have googled (I promise) but I can't find any examples... basically my code is getting bogged down in if/else if/ else statements, and I am wondering if there is a shorthand. I know (I think) that you can do if/else like this:

variable = (condition) ? trueValue : falseValue;

but can you add an else if into the code?

thanks in advance.

07-02-2011, 04:56 PM
Try this:

variable = (condition) ? trueValue : ((condition) ? trueValue : falseValue);

07-02-2011, 06:23 PM
Word of caution here, it is not recommended to nest ternary statements....as they can sometimes lead to unexpected results.

07-02-2011, 06:42 PM
thank you for the word of caution.

I actually ended up using a switch in the end - partially because it is more intuitive to read (for me, anyway), but I tested MarPlo's code and it worked perfectly.