The interesting thing about the conditional operator (?:) is that hardly anybody knows what it’s called (it’s often just referred to as the ternary operator), but everyone seems to have an opinion on whether it should be used.

The conditional operator is shorthand for an if/else statement; rather than writing

if (condition) {expression 1}
else {expression 2}

we can just write

condition ? expression 1 : expression 2

Coworkers arguingI’ve had one code reviewer who was extremely against ever using this, to the point where I replaced the one I was using with an if/else statement (at the expense of clarity) just to end the argument (knowing that I was unlikely to work with him again anyway). The conditional operator can certainly be misused; consider something like the following:

condition1 ? exp1 : condition2 ? expr2 : condition3 ? expr3 : expr4

That’s a bad use of the conditional operator, because the reader has to stop and think through it to understand what’s going on. The equivalent if/else block, on the other hand, is longer but much easier to read:

if (condition1) { exp 1 }
else if (condition2) { expr2 }
else if (condition3) {expr3 }
else {expr4}

Understanding the second block is trivial. Side note: I would normally prefer to have each expression on its own line, but that’s a whole different argument and I’m condensing it a bit for this post. Also, I’m using C# here, in which the conditional operator is right-associative; that’s not true in all languages.

On the other hand, if you have a block that looks like this:

if (var1 % 2 == 0) {var2 = Parity.Even}
else { var2 = Parity.Odd }

Then the conditional operator version is just as easy to read, if not easier:

var2 = (var1 % 2 == 0) ? Parity.Even : Parity.Odd;

This version also has the advantage of making it obvious that, regardless of the outcome of the test, var2 is being set. There’s no way to accidentally set var2 in one case and var3 in the other, which removes one small possibility for bugs. It emphasizes the operation being done, while the if/else version emphasizes the condition.

Long story short: use the conditional operator when it improves the readability of the code, don’t use it when it doesn’t.  Here are some more bad examples:

a = expression : true ? false;

a = b != null ? b : null;

a = (b != null ? b : c); // use a = b ?? c;

Again, this just comes down to a simple rule: given two or more ways to code something, tend towards whichever method requires the least amount of concentration from the reader. The sanity you save could be your own.