Control Statements In C#

This article has been excerpted from book "Visual C# Programmer's Guide"

Control statements give you additional means to control the processing within the applications you develop. This section explores the syntax and function of the if, switch, do-while, for, foreach, goto, break, continue, and return statements.

If-then-else

 
The if statement has three forms: single selection, if-then-else selection, and multicase selection. Listing 5.23 contains an example of each form.

Listing 5.23: If-Else-ElseIf Example 1
  1. //single selection  
  2. if (i > 0)  
  3.     Console.WriteLine("The number {0} is positive", i);  
  4. //if-then-else selection  
  5.   
  6. if (i > 0)  
  7.     Console.WriteLine("The number {0} is positive", i);  
  8. else  
  9.     Console.WriteLine("The number {0} is not positive", i);  
  10.   
  11. //multicase selection  
  12. if (i == 0)  
  13.     Console.WriteLine("The number is zero");  
  14. else if (i > 0)  
  15.     Console.WriteLine("The number {0} is positive", i);  
  16. else  
  17.     Console.WriteLine("The number {0} is negative", i);  
The variable i is the object of evaluation here. The expression in an if statement must resolve to a boolean value type.
  1. // Compiler Error  
  2. if (1)  
  3.     Console.WriteLine("The if statement executed");  
  4. Console.ReadLine();  
When the C# compiler compiles the preceding code, it generates the error "Constant value 1 cannot be converted to bool."

Listing 5.24 shows how conditional or (||) and conditional and (&&) operators are used in the same manner.

Listing 5.24: If-Then-Else Example 2
  1. //Leap year  
  2. int year = 1974;  
  3. if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)  
  4.     Console.WriteLine("The year {0} is leap year ", year);  
  5. else  
  6.     Console.WriteLine("The year {0} is not leap year ", year);  

Switch

 
From the example in Listing 5.25, you can see that the switch statement is similar to an if-else ifelse if-else form of an if statement.

Listing 5.25: Switch Example 1
  1. string day = "Monday";  
  2. Console.WriteLine("enter the day :");  
  3. day = Console.ReadLine();  
  4.   
  5. switch (day)  
  6. {  
  7.     case "Mon":  
  8.         break;  
  9.     case "Monday":  
  10.         Console.WriteLine("day is Monday: go to work");  
  11.         break;  
  12.     default:  
  13.         Console.WriteLine("default");  
  14.         break;  
  15. }  
  16.   
  17. switch (strVal1)  
  18. {  
  19.     case "reason1":  
  20.         goto case "reason2"// this is a jump to mimic fall-through  
  21.     case "reason2":  
  22.         intOption = 2;  
  23.         break;  
  24.     case "reason 3":  
  25.         intOption = 3;  
  26.         break;  
  27.     case "reason 4":  
  28.         intOption = 4;  
  29.         break;  
  30.     case "reason 5":  
  31.         intOption = 5;  
  32.         break;  
  33.     default:  
  34.         intOption = 9;  
  35.         break;  
  36. }  

Do-While

 
The while loop allows the user to repeat a section of code until a guard condition is met. Listing 5.27 presents a simple while loop designed to find out the number of digits in a given value.

Listing 5.27: While Example
  1. //find out the number of digits in a given number  
  2. int i = 123;  
  3. int count = 0;  
  4. int n = i;  
  5.   
  6. //while loop may execute zero times  
  7. while (i > 0)  
  8. {  
  9.     ++count;  
  10.     i = i / 10;  
  11. }  
  12. Console.WriteLine("Number {0} contains {1} digits.", n, count);  
For a given number i = 123, the loop will execute three times. Hence the value of the count is three at the end of the while loop.

This example has one logical flaw. If the value of i is 0, the output of the code will be "Number 0 contains 0 digits." Actually, the number 0 contains one digit. Because the condition of the while loop i > 0 is false from the beginning for the value i = 0, the while loop does not even execute one time and the count will be zero. Listing 5.28 presents a solution.

Listing 5.28: Do Example
  1. //find out the number of digits in a given number  
  2. int i = 0;  
  3. int count = 0;  
  4. int n = i;  
  5. do  
  6. {  
  7.     ++count;  
  8.     i = i / 10;  
  9. while (i > 0);  
  10. Console.WriteLine("Number {0} contains {1} digits.", n, count);  
The do-while construct checks the condition at the end of the loop. Therefore, the do-while loop executes at least once even though the condition to be checked is false from the beginning. 
 

For

 
The for loop is useful when you know how many times the loop needs to execute. An example of a for statement is presented in Listing 5.29.

Listing 5.29: For Example 1
  1. for (int i = 0; i < 3; i++)  
  2.     a(i) = "test"  
  3.   
  4. for (string strServer = Console.ReadLine();  
  5. strServer != "q" && strServer != "quit";  
  6. strServer = Console.ReadLine())  
  7. {  
  8.     Console.WriteLine(strServer);  
  9. }  
Listing 5.30 shows the use of a for loop with the added functionality of break and continue statements.
  1. //For loop with break and continue statements  
  2. for (int i = 0; i < 20; ++i)  
  3. {  
  4.    if (i == 10)  
  5.        break;  
  6.    if (i == 5)  
  7.        continue;  
  8.    Console.WriteLine(i);  
  9. }  
The output of the code in the listing is as follows,

0
1
2
3
4
6
7
8
9

When i become 5, the loop skips over the remaining statements in the loop and goes back to the post loop action. Thus, 5 is omitted from the output. When i become 10, the program will break out of the loop.
 

ForEach

 
The foreach statement allows the iteration of processing over the elements in arrays and collections. Listing 5.31 contains a simple example.

Listing 5.31: ForEach Example 1
  1. //foreach loop  
  2. string[] a = { "Chirag""Bhargav""Tejas" };  
  3. foreach (string b in a)  
  4. Console.WriteLine(b);  
Within the foreach loop parentheses, the expression consists of two parts separated by the keyword in. To the right of in is the collection, and to the left is the variable with the type identifier matching whatever type the collection returns.

Listing 5.32 presents a slightly more complex version of the foreach loop.

Listing 5.32: ForEach Example 2
  1. Int16[] intNumbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };  
  2. foreach (Int16 i in intNumbers)  
  3. {  
  4.    System.Console.WriteLine(i);  
  5. }  
Each iteration queries the collection for a new value for i. As long as the collection intNumbers returns a value, the value is put into the variable i and the loop will continue. When the collection is fully traversed, the loop will terminate.
 

GoTo

 
You can use the goto statement to jump to a specific segment of code, as shown in Listing 5.33. You can also use goto for jumping to switch cases and default labels inside switch blocks. You should avoid the overuse of goto because code becomes difficult to read and maintain if you have many goto jumps within your code.

Listing 5.33: GoTo Example
  1. label1:  
  2.       ;  
  3.       //...  
  4.       if (x == 0)  
  5.           goto label1;  
  6.       //...  

Break

 
The break statement, used within for, while, and do-while blocks, causes processing to exit the innermost loop immediately. When a break statement is used, the code jumps to the next line following the loop block, as you'll see in Listing 5.34.

Listing 5.34: Break Example
  1. while (true)  
  2. {  
  3.     //...  
  4.     if (x == 0)  
  5.         break;  
  6.     //...  
  7. }  
  8. Console.WriteLine("break");  

Continue

 
The continue statement (shown in Listing 5.35) is used to jump to the end of the loop immediately and process the next iteration of the loop.

Listing 5.35: Continue Example
  1. int x = 0;  
  2. while (true)  
  3. {  
  4.     //...  
  5.     if (x == 0)  
  6.     {  
  7.         x = 5;  
  8.         continue;  
  9.     }  
  10.     //...  
  11.   
  12.     if (x == 5)  
  13.         Console.WriteLine("continue");  
  14.     //...  
  15. }  

Return

 
The return statement is used to prematurely return from a method. The return statement can return empty or with a value on the stack, depending upon the return value definition in the method (Listing 5.36 shows both). Void methods do not require a return value. For other functions, you need to return an appropriate value of the type you declared in the method signature.

Listing 5.36: Return Example

  1. void MyFunc1() {  
  2.     // ...  
  3.     if (x == 1) return;  
  4.     // ...  
  5. }  
  6. int MyFunc2() {  
  7.     // ...  
  8.     if (x == 2) return 1919;  
  9.     // ...  
  10. }  

Conclusion

 
Hope this article would have helped you in understanding control statements in C#. See other articles on the website on .NET and C#.



MCN Solutions Pvt. Ltd.
MCN Solutions is a 17 year old custom software development and outsourcing services provider.