O'Reilly logo

C# 5.0 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix H Control Statements

Control statements tell an application which other statements to execute under a particular set of circumstances.

The two main categories of control statements are decision statements and looping statements. The following sections describe the decision and looping statements provided by C#.

Decision Statements

A decision statement represents a branch in the program. It marks a place where the program can execute one set of statements or another or possibly no statements at all.

if-else Statements

The if=else statement has the following syntax.

if (condition1) block1;
else if (condition2) block2;
else if (condition3) block3;
...
else blockElse;

The program evaluates each condition and executes the first block for which the condition is true.

If none of the conditions is true, then the final blockElse block is executed. If the final else statement and the blockElse are not provided, no code is executed.

Each block could be a single statement or a sequence of statements included in braces.

switch

A switch statement lets a program execute one of several pieces of code based on a test value. The switch statement is roughly equivalent to a sequence of if-else statements.

The basic syntax is as follows.

switch (value)
{
    case expression1:
statements1;
        break;
    case expression2:
statements2;
        break;
    ...
    «default:
statementsDefault
        break;»
}

The program compares value to the expressions until it finds one that matches or it runs out of expressions to test. The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required