Statements

Statements in C# include decision control and looping. Those statements that are not decisions or loops are closed with semicolons (;). The following sections describe the decision and looping statements in C#. For statements that evaluate a condition, such as if, while, do, and for, the condition must always evaluate to a Boolean value of true or false.

The if Statement

if statements are used to make a logical decision and branch to a block of code based on whether that logical decision evaluated to a value of true or false. Listing 2.3 demonstrates a simple if statement.

Listing 2.3 A Simple if Statement (SimpleIf.cs)
 using System; class SimpleIf {    static void Main()    {       bool myCondition = true;       if (myCondition == true)       {          Console.WriteLine("myContition is {0}", myCondition);          Console.ReadLine();       }    } } 

The WriteLine and ReadLine statements within the if block of Listing 2.3 are guaranteed to execute because myCondition is hard-coded to true. These statements would not execute if the condition was false.

if statements can also have multiple conditions, identified by else if branches. Listing 2.4 shows how this works.

Listing 2.4 An if Statement with else if Branches (IfElse.cs)
 using System; class IfElse {    static void Main()    {       int myNum = 54;       if (myNum > 0 && myNum <= 25)       {          Console.WriteLine("myNum > 0 && myNum <= 25.");       }       else if (myNum > 25 && myNum <= 50)       {          Console.WriteLine("myNum > 25 && myNum <= 50.");       }       else if (myNum > 50 && myNum <= 75)       {          Console.WriteLine("myNum > 50 && myNum <= 75.");       }       else       {          Console.WriteLine("myNum is greater than 75.");       }       Console.ReadLine();    } } 

Listing 2.4 shows why it would be necessary to use an if statement with else if branches rather than a switch statement (shown next). When the decision must be expressed as ranges or calculated functions, a switch statement, which only evaluates constant values, won't work. The else branch handles conditions that don't evaluate to true in any of the other branches.

The switch Statement

A switch statement is similar to an if statement in functionality in that it allows code to take multiple branches. However, the primary difference is that switch statements only evaluate integers, enums (described in the "Enums" section of this chapter), or strings. Listing 2.5 demonstrates a switch statement.

Listing 2.5 A switch Statement (SwitchCase.cs)
 using System; class SwitchCase {    static void Main()    {       short myCase = 2;       switch (myCase)       {          case 0:          case 1:             Console.WriteLine("myCase is 0 or 1.");             break;          case 2:             Console.WriteLine("myCase is 2.");             break;          default:             Console.WriteLine("myCase is unrecognized.");             break;       }       Console.ReadLine();    } } 

Each case of a switch statement must have a break or goto statement (covered later in this chapter, in the section titled "The break, continue, goto, and return Statements"). This is because case statements are not allowed to fall through, as in C and C++. The only exception is where there are no statements between cases, such as case 0 and case 1 in Listing 2.5.

The while Loop

A while loop will evaluate a condition and continuously execute a block of code as long as that condition is true. Listing 2.6 shows a while loop.

Listing 2.6 A while Loop (WhileLoop.cs)
 using System; class WhileLoop {    static void Main()    {       bool myCondition = true;       while (myCondition == true)       {          Console.WriteLine("myCondition is {0}", myCondition);          myCondition = false;       }       Console.ReadLine();    } } 

In Listing 2.6, code in the while loop executes one time and then exits after the second evaluation. It does this on purpose because I explicitly changed the condition to false within the while loop.

The do Loop

When a block of code should be guaranteed to execute at least one time, a do loop would be the best choice. Listing 2.7 demonstrates how to code a do loop.

Listing 2.7 A do Loop (DoWhileLoop.cs)
 using System; class DoWhileLoop {    static void Main()    {       bool myCondition = true;       do       {          Console.WriteLine("myCondition is {0}", myCondition);          myCondition = false;       }       while (myCondition == true);       Console.ReadLine();    } } 

Listing 2.7 is logically equivalent to the while loop, except that the code is guaranteed to execute at least one time.

The for Loop

If the number of iterations in an array or collection can be determined beforehand, you can use a for loop. Also, if there is a need to control how much of a loop is visited, or the code needs to traverse the collection backward, a for loop is the best choice. A for loop is shown in Listing 2.8.

Listing 2.8 A for Loop (ForLoop.cs)
 using System; class ForLoop {    static void Main()    {       int count = 2;       for (int i=0; i < count; i++)       {          Console.WriteLine("i: {0}", i);       }       Console.ReadLine();    } } 

In Listing 2.8, the index is initialized, int i=0, in the for loop, making it local to the for loop. If it should be used outside the for loop, it must be declared before the for loop begins.

The foreach Loop

A foreach loop is easy to use for arrays and collections, when every element in the array or collection is visited. Keep in mind that a foreach loop only provides read access to the array or collection members. If the code must change the collection values on the fly, a for loop would be a better choice. Use a foreach loop when the simpler syntax is preferred. Listing 2.9 demonstrates the foreach loop.

Listing 2.9 A foreach Loop (ForEachLoop.cs)
 using System; class ForEachLoop {    static void Main()    {       string[] fruits = {"Apple", "Banana", "..."};       foreach (string fruit in fruits)       {          Console.WriteLine("fruit: {0}", fruit);       }       Console.ReadLine();    } } 

The fruits variable in Listing 2.9 is an array (discussed in the "Arrays" section of this chapter) holding three strings. A benefit of the foreach is that it will automatically stop when it has read each item of the array. The tradeoff of this simpler syntax is that each item read from the collection may not be modified. The internal workings of the foreach loop are explained in Chapter 3 in the section that covers interfaces.

The break, continue, goto, and return Statements

Other statements that change the flow of control in an algorithm are the break, continue, goto, and return statements. The break statement was demonstrated previously in the switch statement listing, where it was required to end a case block. It can also be used in normal algorithms to leave its enclosing loop or decision statement. Listing 2.10 shows how to use a break statement.

Listing 2.10 Using the break Statement (BreakStatement.cs)
 using System; class BreakStatement {    static void Main()    {       byte count = 7;       for (byte i=0; i < count; i++)       {          Console.WriteLine("i: {0}", i);          if (i == 3)             break;       }       Console.ReadLine();    } } 

Listing 2.10 simulates detecting some condition that would make a loop terminate prematurely. In such a scenario, the break statement could bring optimizations that would be difficult to achieve with other logic.

A continue statement in a loop will cause execution of the algorithm it is currently executing to stop, and control will return to the evaluation statement of the loop. Listing 2.11 shows the continue statement.

Listing 2.11 Using the continue Statement (ContinueStatement.cs)
 using System; class ContinueStatement {    static void Main()    {       byte count = 7;       for (byte i=0; i < count; i++)       {          if (i % 2 == 0)             continue;          Console.WriteLine("i: {0}", i);       }       Console.ReadLine();    } } 

Another optimization, the continue statement, says that the rest of the code in this iteration should not be executed, but the loop should keep running. The continue is more rare than the break statement, but could be used in a practical manner on occasion.

A goto statement will branch out of an enclosing block to a specified label. They can never branch into a block, but only outside of its enclosing block to a more global scope. A goto may be used in the switch statement, where multiple case statements should be executed in order. Listing 2.12 shows how to use a goto statement with a switch statement.

Listing 2.12 Using the goto Statement (GotoStatement.cs)
 using System; class GotoStatement {    static void Main()    {       short myCase = 0;       switch (myCase)       {          case 0:             goto case 1;          case 1:             Console.WriteLine("myCase is 0 or 1.");             break;          case 2:             Console.WriteLine("myCase is 2.");             break;          default:             Console.WriteLine("myCase is unrecognized.");             break;       }       Console.ReadLine();    } } 

Listing 2.12 shows how to use a goto to simulate fall-through in a switch statement a facility missed by some C and C++ programmers. In this scenario, logic in case 1 is executed after logic of case 0.

return statements are used in several places in C#. They can return an integer value from an application, the return type of a method, or the return value of the get accessor of a property or indexer (described in the "Properties and Indexers" section of this chapter). Listing 2.13 shows how to use the return statement with the Main method.

Listing 2.13 Using the return Statement (ReturnStatement.cs)
 using System; class ReturnStatement {    static int Main()    {       int success = 0;       Console.WriteLine("success = {0}", success);       Console.ReadLine();       return success;    } } 

The scenario simulated in Listing 2.13 shows how an application can return values for a command-line script or batch program to read. If there was an error, the program would return something other than 0 so that the script could make a decision.



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net