Program Control

   

To direct the flow of program execution, the .NET languages support several control-flow statements. These act as you would expect. The following sections examine each, beginning with the popular if statement.

If Statements

There are two types of if statements, both of which require the use of a Boolean expression. These are the syntaxes for the most basic if statement:

VB

 If boolean expression Then      ' Do some stuff here  End If 

C#

 if( boolean expression)  {      // Do some stuff here  } 

JScript

 if( boolean expression)  {      // Do some stuff here  } 

Depending on the value of the Boolean expression, the body of the if statement may or may not be executed. If the expression evaluates to true, the body is executed. If the expression evaluates to false, the body of code is skipped .

Take, for example, the following C# statement:

 if( x < 10 )  {      Console.WriteLine("Hello, the expression is true.\n" );  } 

When the above statement is encountered , the Boolean expression is evaluated:

 x < 10 

The body of code following the if statement executes only in cases where x is less than 10. If x is equal to (or greater than) 10, the block of code is skipped and program execution continues immediately after the closing brace (}).

This form of control flow is often called an if-then statement, because it follows the logic of "if the expression is true, then execute this body of code."

The second form of the if statement uses the keyword else , directing program execution along one of two distinct routes:

VB

 If boolean expression Then      ' Do stuff here  Else      ' Or else do stuff here  End If 

C#

 if( boolean expression)  {      // Do stuff here  }  else  {      // Or else do stuff here  } 

JScript

 if( boolean expression)  {      // Do stuff here  }  else  {      // Or else do stuff here  } 

If the Boolean value evaluates to true, the block of code immediately following that value is executed. If the expression evaluates to false, the else block is executed.

This form of control flow is often called an if-then-else statement, because it follows the logic of "if the expression is true, then execute this body of code, or else execute this one."

The last C# example looks like this, using the if-then-else statement:

 if( x < 10 )  {      Console.WriteLine("Hello, the expression is true.\n" );  }  else  {      Console.WriteLine("Hello, the expression is not true.\n" );  } 

At any given time, only one of the above blocks of code is executed. At no time are both executed, because the value of the Boolean expression directs the flow of execution in only one of two possible directions, not both.

An additional aspect of control can be added to the if statement using the following else-if construct:

VB

 If boolean expression Then      'Do Stuff here  ElseIf boolean expression Then      ' Or maybe do stuff here  Else      ' Or else do stuff here  End If 

C#

 if( boolean expression )  {      // Do stuff here  }  else if( boolean expression )  {      // Or maybe do stuff here  }  else  {      // Or else do stuff here  } 

JScript

 if( boolean expression )  {      // Do stuff here  }  else if( boolean expression )  {      // Or maybe do stuff here  }  else  {      // Or else do stuff here  } 

Applying this to the preceding C# example, you can exercise more precise control over the flow of program execution:

 if( x < 10 )  {      Console.WriteLine("Hello, the expression is true.\n" );  }  else if( x < 20 )  {      Console.WriteLine("Hello, the second expression is true.\n" );  }  else  {      Console.WriteLine("Hello, neither the first or second      expression is true.\n" );  } 

Switch and Select Statements

The switch (for C# and JScript) or select (for VB) statement is similar in nature to the if-then-else statement, although it makes the programmer's job a lot easier when a number of else clauses are needed:

VB

 Select Case expression      Case constant1          ' Do stuff if the expression evaluates to constant1      Case constant2          ' Do stuff if the expression evaluates to constant2      Case constant3          ' Do stuff if the expression evaluates to constant3      Case Else          ' Do stuff here if the expression doesn't evaluate to any            of the explicit cases  End Select 

C#

 switch( expression )  {      case constant1:          // Do stuff if the expression evaluates to constant1         break;      case constant2:          // Do stuff if the expression evaluates to constant2         break;      case constant3:          // Do stuff if the expression evaluates to constant3         break;      default:          // Do stuff here if the expression doesn't evaluate to             any of the explicit cases          break;  } 

JScript

 switch( expression )  {      case constant1:          // Do stuff if the expression evaluates to constant1         break;      case constant2:          // Do stuff if the expression evaluates to constant2         break;      case constant3:          // Do stuff if the expression evaluates to constant3         break;      default:          // Do stuff here if the expression doesn't evaluate to             any of the explicit cases          break;  } 

When the execution enters a switch or select statement, the expression is evaluated against that statement.

The value of the expression is then converted to the int type, as are all the case constants. Beginning with the first case statement, the value of the expression is compared to the value of the case constant. If the two values are equal, any code following the colon is executed, until the break statement (C# and JScript only) is reached. If the expression doesn't match the case constant, it is compared to the next one. This process continues until the default or else case is reached at which point the code for this case is executed.

When a case is executed in C# and JScript, the break statement is used to stop the flow of execution. When a break statement is reached, execution stops immediately and resumes after the closing brace (}) of the switch body. Because execution terminates when the first break is encountered, the default case is executed only if no match is found between the value of the switch expression and all other cases.

In VB, there's an implicit break statement before the start of each case. For this reason, program control can't fall through to the next case in VB as it can in C# and JScript.

The switch and select statements are particularly useful when a number of cases exist. If you were to try to write more than a half- dozen else clauses in an if-else statement, you'd find the process a bit tedious . It would be even more difficult to read the code. With a switch or select statement, however, the code is clean and easy to read. You can use as many cases as you need, without making a mess of the code. And, if none of the cases match the value of your expression, you can rely on the default case being executed.

Be certain to end each C# and JScript case with a break statement. If you don't, all cases following the matching one will be executed as well! This is an undesirable condition known as fall-through, and can be avoided if you match a break statement with every case.

Loops

Control-flow statements include a number of loops:

  • while loops

  • do-while loops

  • for loops

While and Do-While Loops

The while and do-while loops in C# and JScript are identical to those in C, and in VB they are similar:

VB

 While Boolean expression      ' Do something  While End  Do While Boolean expression      ' Do something  Loop 

C#

 while( boolean expression )  {      // Do something  }  do  {      // Do something  } while( boolean expression ) 

JScript

 while( boolean expression )  {      // Do something  }  do  {      // Do something  } while( boolean expression ) 

In the while loop, the Boolean expression is evaluated. The value of this expression determines whether the body of the loop is executed. If the expression evaluates to true, the loop is executed. If it's false, it does not. Each time through the body of the while loop, the expression is reevaluated. The following loop (in C#) continues until the expression evaluates to false:

 int x = 0;  while( x++ < 10 )  {      Console.WriteLine("The while loop is being executed.\n" );  } 

In the preceding example, the body of the loop continues to execute as long as x is less than 10. Because you increment the value of x by one (x++) in the expression itself, the loop executes 10 times.

Note that the increment could have also taken place in the body of the loop itself, as follows:

 while( x < 10 )  {      x++;      Console.WriteLine("The while loop is being executed.\n" );  } 

With the do-while loop, the body of the loop executes once before the expression is ever evaluated. This ensures that your loop code is executed at least once, regardless of how the expression evaluates.

 do  {      Console.WriteLine("The while loop is being executed.\n" );  } while( x++ < 10 ); 

As with the while loop, you could have incremented the expression inside the loop body rather than inside the expression:

 do  {      Console.WriteLine("The while loop is being executed.\n" );      x++;  } while( x < 10 ); 

The while loop is by far the more popular of the two, although the do-while loop has the advantage of executing your code at least once, no matter what the expression evaluates to.

Be sure to change your expression value either inside the body of the while or do-while loop or in the expression itself. If the value never changes, the expression always remains true and the loop executes indefinitely.

For Loops

The for loop repeats program execution as controlled through a series, which terminates when a certain limit is reached. It continues looping until the specified limit is reached, at which point the loop is broken and execution resumes immediately after the loop body code ends:

VB

 For expression to expression      ' Do something  Next 

C#

 for( expression; booleanExpression; expression)  {      // Do something  } 

JScript

 for( expression; booleanExpression; expression)  {      // Do something  } 

For C# and JScript, the first expression initializes the loop variable. The second is a Boolean expression that specifies the limit. The third and final expression specifies how the loop variable is to change each time through the loop.

Consider the following C# example:

 int x;  for( x=0; x<10; x++ )  {      Console.WriteLine("The while loop is being executed.\n" );  } 

The first expression, x=0, sets the loop variable to zero. The loop executes until the second expression, x<10, evaluates to true. And the final expression, x++, increments the loop variable by one every time through the loop.

In VB, the first expression sets a counter to an initial value, then indicates at which point the counter is to stop. The following VB for a loop counts from 1 to 10:

 For x=1 to 10      ' Do something  Next 
C# and JScript Break and Continue Statements

In addition to the if , switch , while , and do-while control-flow constructs, C# and JScript support two additional statements: break and continue . These are considered "jump" statements, because they allow the flow of program execution to branch out in directions not seen with the standard control-flow statements already discussed.

As you've seen, the switch statement makes use of the break statement to terminate a case's execution. However, those break statements were used without labels. Both break and continue can be used with an optional label, specifying exactly where the execution is to be transferred. Without a label, break and continue behave exactly as they do in C.

Take a look at the following C# example of a labeled break statement in a switch occurring in a while loop:

 int x = 0;  enterLoop:  while( x++ < 10 )  {      Console.WriteLine("The while loop is being executed.\n" );      switch( x )      {          case 0: Console.WriteLine( "Inside switch, x: 0\n" );              break;          case 1: Console.WriteLine( "Inside switch, x: 1\n" );              break;          case 2: Console.WriteLine( "Inside switch, x: 2\n" );              break;          default:              if( x == 5 )              {                  Console.WriteLine("Break out of switch and while.\n");                  break enterLoop;              }              break;      }      Console.WriteLine( "Out of switch, back in while loop.\n" );  }; 

Each time through the while loop, the switch statement is encountered. Up until the time x is equal to 5, standard break statements are used to break out of the switch statement and back into the while loop. However, when x is 5, the line is executed:

 break enterLoop; 

When this happens, not only does the break occur for the switch statement, but also for the entire while loop! If this labeled break were not present, the while loop would execute ten times. However, it executes only five times, because the labeled break kicks the flow of control out of both the switch and while loop.

Although the break statement is used to break out of the loop, a labeled continue statement redirects execution to the label itself.

Unlike break , the labeled continue statement transfers control of program execution to the iteration following the label:

 int x = 0;  enterLoop:  while( x++ < 5 )  {      Console.WriteLine( "Inside the while loop.\n" );      for( int i=0; i<10; i++ )      {         Console.WriteLine( "Inside for loop.\n" );         if( i == 5 )         {             Console.WriteLine( "Out of for loop.\n" );             continue enterLoop;         }      }      Console.WriteLine( "Out of for loop, back in while.\n" );  } 

Here, I've created a for loop inside a while loop. Each time through the while loop, the for loop is executed until i equals 5, at which point program execution jumps out of the for loop and goes to the first statement inside the while loop:

 Console.WriteLine ("Inside while loop, iteration.\n"); 

When this happens the final output line in the while loop isn't executed, because the flow of execution has been rerouted to its beginning. However, if I hadn't included a label, the break statement alone would have rerouted the execution to the first line of code following the for loop. In that case, the final output line would have been executed. There are actually four jump statements (the throw statement is covered in the following section):

break

continue

return

throw

The return statement is used to return program execution to the caller of a code segment, such as when a method has been invoked. At any point in the method, a return statement can return the flow of control back to the caller of that method. The throw statement is used to signal a runtime exception, as described in the following section, which interrupts the flow of program execution while a handler is sought to deal with that exception.

   


Special Edition Using ASP. NET
Special Edition Using ASP.Net
ISBN: 0789725606
EAN: 2147483647
Year: 2002
Pages: 233

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