Benefits of using the conditional ?: (ternary) operator

This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...

In languages like C++ and C#, you can define local readonly fields (within a method body) using them. This is not possible with a conventional if/then statement because the value of a readonly field has to be assigned within that single statement:

readonly int speed = (shiftKeyDown) ? 10 : 1;

is not the same as:

readonly int speed;  
if (shifKeyDown)  
    speed = 10;    // error - can't assign to a readonly
else  
    speed = 1;     // error  

In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:

MoveCar((shiftKeyDown) ? 10 : 1);

...may generate less code than having to call the same method twice:

if (shiftKeyDown)
    MoveCar(10);
else
    MoveCar(1);

Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:

object thing = (reference == null) ? null : reference.Thing;

... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.

Of course, just because it is useful does not mean it is the best thing to use in every case. I'd advise only using it for short bits of code where the meaning is clear (or made more clear) by using ?: - if you use it in more complex code, or nest ternary operators within each other it can make code horribly difficult to read.


I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.

if (a > 0)
    answer = compute(a, b, c, d, e);
else
    answer = compute(-a, b, c, d, e);

With a ternary operator, this could be accomplished with the following.

answer = compute(a > 0 ? a : -a, b, c, d, e); 

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

Good example:

int result = Check() ? 1 : 0;

Bad example:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;