Most of the time I am "Mr. Best Practice," but I have one flaw—I think the conditional ternary operator is great! Yes, we've heard it before—they are "hard to read" or "they are error prone," but I disagree. If you understand how it works, and you don't over-complicate your syntax, it's not hard to read or error prone at all. In fact, I believe if used correctly it can increase readibility by decreasing code clutter.
What is it? The conditional ternary operator is simply a conditional operator that accepts three operands. It takes a condition, and then depending on that condition returns one of two operands. Here I demonstrate the basic syntax..
variable = condition ? true part : false part;
Here are a few examples that may be easier to grasp..
int i = true ? 0 : 1; // i = 0
int j = false ? 0: 1; // j = 1
The ternary statement is basically just a short-hand way of writing five lines of code..
int i; // i = 0
if (true)
i = 0;
else
i = 1;
Do you use VB.NET? Just use the IIf function instead. The following two lines are in different languages (C# and VB.NET, respectively) but they produce the same result.
int i = true ? 1 : 2; // i = 1
Dim i as Integer = IIf(true, 1, 2) ' i = 1
Now the problem with the ternary operator is that people sometimes get crazy with it. You can embed a ternary statement inside of another ternary statement, just like you can embed an if inside of another if..
int k = true ? false ? 2 : 5 : 1; // k = 5
.. which is the same as ..
int k = true ? (false ? 2 : 5) : 1;
.. which is the same as ..
int k;
if (true)
{
if (false)
i = 2;
else
i = 5;
}
else
i = 1;
It doesn't stop there, you can put anything inside a ternary that's considered in-line code. That is, anything that doesn't require a line break. Here's a little exercise for you. Work it out in your head, then compile it to see what the answer is. (Of course, you'd never want to do anything like this in a real project!)
bool a = true, b = false, c = true;
bool d = a || b ? c && b ? a || c : b && c : a || c ? b || c : a && b;
As you can see, conditional statements that use the ternary operator can quickly get out of hand, but as long as you don't get crazy they should still be readable. If they're not readable, or readability is questionable, then you should use the classic if/else block instead.