Control Statements In C#

Introduction

This article has been excerpted from the 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. The below code contains an example of each form.

Example 1

//single selection  
if (i > 0)  
    Console.WriteLine("The number {0} is positive", i);  
//if-then-else selection  
  
if (i > 0)  
    Console.WriteLine("The number {0} is positive", i);  
else  
    Console.WriteLine("The number {0} is not positive", i);  
  
//multicase selection  
if (i == 0)  
    Console.WriteLine("The number is zero");  
else if (i > 0)  
    Console.WriteLine("The number {0} is positive", i);  
else  
    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.

// Compiler Error  
if (1)  
    Console.WriteLine("The if statement executed");  
Console.ReadLine();  

When the C# compiler compiles the preceding code, it generates the error "Constant value 1 cannot be converted to bool."

The code below shows how conditional or (||) and conditional and (&&) operators are used in the same manner.

Example 2

//Leap year  
int year = 1974;  
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)  
    Console.WriteLine("The year {0} is leap year ", year);  
else  
    Console.WriteLine("The year {0} is not leap year ", year); 

Switch

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

Example

string day = "Monday";  
Console.WriteLine("enter the day :");  
day = Console.ReadLine();  
  
switch (day)  
{  
    case "Mon":  
        break;  
    case "Monday":  
        Console.WriteLine("day is Monday: go to work");  
        break;  
    default:  
        Console.WriteLine("default");  
        break;  
}  
  
switch (strVal1)  
{  
    case "reason1":  
        goto case "reason2"; // this is a jump to mimic fall-through  
    case "reason2":  
        intOption = 2;  
        break;  
    case "reason 3":  
        intOption = 3;  
        break;  
    case "reason 4":  
        intOption = 4;  
        break;  
    case "reason 5":  
        intOption = 5;  
        break;  
    default:  
        intOption = 9;  
        break;  
}  

Do-While

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

While Example

//find out the number of digits in a given number  
int i = 123;  
int count = 0;  
int n = i;  
  
//while loop may execute zero times  
while (i > 0)  
{  
    ++count;  
    i = i / 10;  
}  
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. The code below presents a solution.

Do Example

//find out the number of digits in a given number  
int i = 0;  
int count = 0;  
int n = i;  
do  
{  
    ++count;  
    i = i / 10;  
} while (i > 0);  
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 Loop

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 the below code.

Example 1

for (int i = 0; i < 3; i++)  
    a(i) = "test"  
  
for (string strServer = Console.ReadLine();  
strServer != "q" && strServer != "quit";  
strServer = Console.ReadLine())  
{  
    Console.WriteLine(strServer);  
} 

 The code below shows the use of a for loop with the added functionality of break and continue statements.

Example 2

//For loop with break and continue statements  
for (int i = 0; i < 20; ++i)  
{  
   if (i == 10)  
       break;  
   if (i == 5)  
       continue;  
   Console.WriteLine(i);  
}  

Output

Output

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 Loop

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

Example 1

//foreach loop  
string[] a = { "Chirag", "Bhargav", "Tejas" };  
foreach (string b in a)  
Console.WriteLine(b);  

Within the foreach loop parentheses, the expression consists of two parts separated by the keyword in. To the right of it is the collection, and to the left is the variable with the type identifier matching whatever type the collection returns.

The code below presents a slightly more complex version of the foreach loop.

Example 2

Int16[] intNumbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };

foreach (Int16 i in intNumbers)
{
    System.Console.WriteLine(i);
}

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 Statement

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.

Example

label1:  
      ;  
      //...  
      if (x == 0)  
          goto label1;  
      //...  

Break Statement

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.

Example

while (true)  
{  
    //...  
    if (x == 0)  
        break;  
    //...  
}  
Console.WriteLine("break");  

Continue Statement

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.

Example

int x = 0;  
while (true)  
{  
    //...  
    if (x == 0)  
    {  
        x = 5;  
        continue;  
    }  
    //...  
  
    if (x == 5)  
        Console.WriteLine("continue");  
    //...  
}  

Return Statement

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.

Example

void MyFunc1() {  
    // ...  
    if (x == 1) return;  
    // ...  
}  
int MyFunc2() {  
    // ...  
    if (x == 2) return 1919;  
    // ...  
}  

Conclusion

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


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