The logic if-else statement, in the below class, is as short as c# will allow, or can this statement be even shorter?
The logic structure ?: here on MSDN is a short-cut in some circumstances but not for the below?
class Stats
{
public int Total = 0;
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
void Update(Boolean correctKey)
{
//correctKey ? Correct++ : Missed++; //incorrect syntax for this situation as the ? operator is used to set a value
if (correctKey==true) Correct++; else Missed++; //shortest c# syntax?
}
}
The conditional operator is intended to be used with assignments, not as a generalized replacement for the
if/elsestatements. 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:
This sets the value of variable
ato objectxif it is not null, or if it is, objecty. 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 intoif/elseblocks.(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/elseblock 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/elseblocks into a single line: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.