Flow of Control Constructs

Team-Fly    

 
.NET and COM Interoperability Handbook, The
By Alan Gordon
Table of Contents
Chapter Four.  A Quick Introduction to C#

Flow of Control Constructs

C# supports the same flow of control statements that you are familiar with from C and C++. The structure of an if statement is almost exactly the same as C and C++. C# also supports switch statements and adds the very useful ability to switch on a string. There are for, do, and while loops and a new loop called the foreach loop that you will probably find yourself using more than any other type of loop.

Let's start by looking at the if statement. The following code shows an example of a simple if statement in C#:

 int x=0, y=1; if (x > y)     System.Console.WriteLine("x is greater than y"); 

You can also use else if and else clauses as follows :

 int x=0, y=1; if (x > y)     System.Console.WriteLine("x is greater than y"); else if (y > x)     System.Console.WriteLine("x is less than y"); else       System.Console.WriteLine("x and y are equal"); 

If you want to have multiple statements within your if block, you use curly braces just like C and C++.

 int x=0, y=1; if (x > y) {     System.Console.WriteLine("X is greater than y");     System.Console.WriteLine("And I am so happy"); } 

Switch statements in C# are very similar to switch statements in C and C++. The following code shows a simple switch statement in C#:

 int intInputValue; string strInput; strInput=Console.ReadLine(); try {     intInputValue=int.Parse(strInput);     switch (intInputValue)     {       case 1:         Console.WriteLine("You entered 1");         break;       case 2:         goto case 3;       case 3:         Console.WriteLine("You entered 2 or 3");         break;       case 4:         goto default;       default:         Console.WriteLine(         "You entered a number > than 3 or < 1");         break;     } } catch {     System.Console.WriteLine("Please enter a number"); } 

Rather than using "goto case 3" on case 2, you can combine case 2 and 3 as follows:

 switch (intInputValue) {     case 1:       Console.WriteLine("You entered 1");       break;     case 2:     case 3:       Console.WriteLine("You entered 2 or 3");       break;     case 4:       goto default;     default:       Console.WriteLine(       "You entered a number > 3 or < 1");       break; } 

There are some differences between C# and C and C++ switch statements. First, the endpoint of each case within the switch statement must not be reachable . There must be either a break or a goto to another case. This eliminates a common source of bugs in C and C++: the unintended fallthrough from one case to another as follows:

 // C++ code switch (intInputValue) {     case 1:       Console.WriteLine("You entered 1");       // falls through to case 2     case 2:       Console.WriteLine("You entered 2");       break;     default:       Console.WriteLine(       "You entered a number > than 2");       break; } 

Notice that there is no break at the end of case 1. With C and C++, case 1 would fall through to case 2. With C#, this code will not compile. If you tried to compile this code with the C# compiler, you will receive the following error:

 Control cannot fall through from one case label ('case 1:') to another 

Another key difference between C# and C and C++ switch statements is that, with C#, you can switch on strings as follows:

 string strInput; Console.WriteLine("Enter a color"); strInput=Console.ReadLine(); switch (strInput) {     case "red":       Console.WriteLine("You entered RED");       break;     case "green":       Console.WriteLine("You entered GREEN");       break;     case "blue":       Console.WriteLine("You entered BLUE");       break;     default:       Console.WriteLine("You entered a non-primary color");       break; } 

The previous code will only work if the user enters the color string in all lower-case characters . You can solve this problem and create a case-insensitive switch statement using the ToLower function on the string that you are switching on.

 switch (strInput.ToLower()) {     case "red":       Console.WriteLine("You entered RED");       break;     case "green":       Console.WriteLine("You entered GREEN");       break;     case "blue":       Console.WriteLine("You entered BLUE");       break;     default:       Console.WriteLine("You entered a non-primary color");       break; } 

C# has very similar looping constructs to C and C++. C# supports while loops, do loops, and for loops. A while loop loops while a condition is true. The condition is evaluated at the beginning of the loop as follows:

 int i=0; while (i < 10) {     Console.WriteLine("i = {0}",i);     i++; } 

A do loop is very similar to a while loop except the condition is evaluated at the end of the loop.

 int i=0; do {     Console.WriteLine("i = {0}",i);     i++; } while (i < 10); 

The for loop gives you a convenient way of looping over a range of values. It is often used for looping through arrays. In this example, I use a for loop to iterate through the array of command-line arguments that the user has passed to a console application.

 public static int Main(string[] args) {     for (int i=0;i<args.Length;i++)       Console.Write(" {0} ", args[i]);     return 0; } 

A better way to iterate over all the elements of a collection or array is to use the foreach loop. Using a for loop to iterate over all the elements of a collection or array is a little more error prone (even though most competent programmers get it right). In order for it to work, you have to set up the initial condition and increment the count correctly. The foreach loop is also syntactically more terse and elegant. You can change the code shown previously to use a foreach loop as follows:

 foreach (string arg in args) {     Console.Write(" {0} ", arg); } 

As you can see, the code here is shorter and more elegant.

With each of the aforementioned looping statements, you can use jump statements. C# supports the following jump statements: continue, break, and goto. A continue statement allows you to skip the portion of the loop after the continue statement for the current iteration. You can think of it as a jump to the end of the loop. The loop will continue if the looping condition is still met, however. The following code demonstrates the use of a continue statement with a foreach loop.

 foreach (string arg in args) {     if (arg=="skip")       continue;     Console.Write(" {0} ", arg); } 

The break statement will exit the loop completely. The flow of control will continue on the first line after the loop. The following code shows a break statement with a for loop:

 for (int i=0; i < 10; i++ ) {     if (i==2)       break;     Console.WriteLine("i = {0}",i); } 

Break statements are also used with switch statements to jump out of each case.

Although its use is widely disparaged, the goto statement is a part of almost every computer language. You use the goto statement to jump directly to a label as follows:

 int[,] a={{1,2,3},{4,5,6},{7,8,9}}; for (int i=0; i < 3; i++ ) {   for (int j=0; j < 3; j++ )   {     if (i==1 && j==1)       goto after_loop;     Console.WriteLine(       "i = {0}, j= {1}, a={2}",i,j,a[i,j]);   } } after_loop: 

This code actually shows one of the few legitimate uses of a goto: to jump completely out of a nested series of loops. If you used a break statement here instead of a goto, you will only get out of the innermost loop. Gotos can also be used in switch statements as follows:

 switch (intInputValue) {     case 1:       Console.WriteLine("You entered 1");       break;     case 2:       goto case 3;     case 3:       Console.WriteLine("You entered 2 or 3");       break;     case 4:       goto default;     default:       Console.WriteLine(           "You entered a number greater than 3 or less           than 1");       break; } 

You cannot use a goto in C# to jump into the middle of a statement. For example, you cannot jump into the middle of a for loop.


Team-Fly    
Top
 


. Net and COM Interoperability Handbook
The .NET and COM Interoperability Handbook (Integrated .Net)
ISBN: 013046130X
EAN: 2147483647
Year: 2002
Pages: 119
Authors: Alan Gordon

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