why make things more complex? why do this:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
instead of this:
if txtNumerator.Text="" {txtNumerator.Text="0";}
why make things more complex? why do this:
txtNumerator.Text =
txtNumerator.Text == "" ? "0" : txtNumerator.Text;
instead of this:
if txtNumerator.Text="" {txtNumerator.Text="0";}
Suppose you wanted to pass either zero or txtNumerator.Text to a method M. How would you do that?
You could say:
Or you could say
The latter is shorter and easier to read.
The larger point here is that statements are useful for their side effects and expressions are useful for their values. If what you want to do is control which of two side effects happens, then use an "if" statement. If what you want to do is control which value gets chosen from two possibilities, then consider using a conditional expression.
UPDATE:
Jenny asks why not just do this?
That's fine if there's just one condition to check. But what if there are, say, four? Now there are sixteen possibilities and writing the "if" statement for it gets messy to say the least:
Instead, you can just say:
It's one expression, so you can use the result directly in an assignment or a function call without having to duplicate the context in which you're using it. That makes a lot of usage scenarios significantly cleaner to write and read. For example:
versus
If you go with the if-then construct, you end up with two assignments to the same variable, in two separate blocks. The ternary form has only one assignment. So there is no need to look at a second block to verify to yourself what both blocks are performing an assignment to the same variable. In that respect I think the ternary form reads better.
On the other hand if C# worked like Ruby and if was an expression, then you could do without the ternary operator and use if-else in that case:
which I would prefer because then the different syntax of ?: could be dropped.
It makes the code more readable in some people opinion, a lot of constructs in the language are syntactic sugar (think about do..while, while..do, and for(..)) and in the end of the day you choose whatever works for you (and your team).
I for example think that the above code should be implemented with an extension method:
There are many standards guides that say not to use the ternary operator. However you could agre that all language feature are unnecessary except for goto and if. I use it when having a multitude of if then elses.