Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.