[Solved] This logic statement is as short as possible


The conditional operator is intended to be used with assignments, not as a generalized replacement for the if/else statements. This is because it produces a result (it is an expression), and that result is then assigned to something else.

For example, consider the following statement:

var a = x != null ? x : y;

This sets the value of variable a to object x if it is not null, or if it is, object y. The goal here is readability. Some programmers find it easier to read a statement with extremely common and straightforward logic like that one in a single line, rather than spread out into if/else blocks.

(This pattern is essentially anachronistic in C# now that we have the null-coalescing operator, but it serves as a good instructional case.)

Conversely, what you’re trying to express here doesn’t really work with the conditional operator since it doesn’t have a result and is not performing an assignment.

In this case, I would say that an if/else block is your best choice. Note that shorter code does not necessarily produce faster code. In fact, in more cases than not, the compiler or the JITer will produce equivalent code that has identical performance. Don’t (ab)use the conditional operator to try and make your code faster, only use it when it makes your code more clear and readable. If readability or expressiveness requires breaking something up into multiple lines, then there’s nothing wrong with doing exactly that.

As other examples show, you can in fact mash the if/else blocks into a single line:

if (correctKey) Correct++; else Missed++;

But this also doesn’t make the code run any faster, it just crams it all together. Like run-on sentences, this should be used judiciously where the meaning is unmistakable.

0

solved This logic statement is as short as possible