Examining the C# "Else" Statement

Some code must check for mutually exclusive conditions. For example, the following code segment stores the maximum of two numbers, a and b, in the variable max:



// Store the maximum of a and b into the variable max.
int max;
// If a is greater than b . . .
if (a > b)
{
// . . .save a as the maximum.
max = a;
}
// If a is less than or equal to b . . .
if (a <= b)
{
// . . .save b as the maximum.
max = b;
}



The second if statement is needless processing because the two conditions are mutually exclusive. If a is greater than b, then a can't possibly be less than or equal to b. C# defines an else clause for just this case. The else keyword defines a block of code that's executed if the if block is not.



The code segment to calculate the maximum now appears as follows:



// Store the maximum of a and b into the variable max.
int max;
// If a is greater than b . . .
if (a > b)
{
// . . .save a as the maximum; otherwise . . .
max = a;
}
else
{
// . . .save b as the maximum.
max = b;
}



If a is greater than b, the first block is executed; otherwise the second block is executed. In the end, max contains the greater of a or b.



Avoiding even the else


Sequences of else clauses can get confusing. Some programmers like to avoid them when doing so doesn't cause even more confusion. You could write the maximum calculation like this:



// Store the maximum of a and b into the variable max.
int max;
// Start by assuming that a is greater than b.
max = a;
// If it is not . . .
if (b > a)
{
// . . . then you can change your mind.
max = b;
}



Some programmers avoid this style like the plague. You see both this style and the "else style" in common use.



Programmers who like to be cool and cryptic often use the ternary operator, :?, equivalent to an if/else on one line:



bool informal = true;
string name = informal : "Chuck" ? "Charles"; // Returns "Chuck".



This evaluates the expression before the colon. If it's true, it returns the expression after the colon but before the question mark. If false, it returns the expression after the question mark. This turns an if/else into an expression.



Generally speaking, use it only rarely because it really is cryptic.










dummies

Source:http://www.dummies.com/how-to/content/examining-the-c-else-statement.html

No comments:

Post a Comment