Flow control in C#

author-image
CIOL Bureau
Updated On
New Update

Here we look at statements that let you control the flow of the execution of
the program. The 3 main categories of the control statements are selection (if,
switch), iteration (while, do…while, for) and jump (break, continue, return).

Advertisment

Now let us look at different flow control statements.

Selection statements:

Advertisment

We start with the selection statements. In C#, there are 2 selection
statements — if and switch.
In the case of selection statements, the test result is used to decide which
path the program execution is to follow.

Advertisment

if

The syntax of this is as follows —

Advertisment
if (expression)
	statement1

// "<" and ">" indicate that this part is optional

The expression is a test that results in a Boolean result (Unlike C or C++,
in case of which we could test for integer values). If the expression evaluates
to true then statement1 will be executed. If there is an else part then, that is
executed when the expression evaluates to false.

The statements that are to be executed can be compound statements. In case of
compound statements, one needs to use curly brackets as follows (just like c,
C++) —

Advertisment
if (expression)
{
	statement11
	statement12
	..
}

Also the statement could itself be an if statement — which then results in nested if as follows —

if (expression1)
{
	if (expression2)
		statement111
	..
}
Advertisment

We can also have multiple else statements as follows —

if (expression1)
	statement1
else if (expression2)
	statement2
else if (expression3)
	statement3
..
else
	..

switch
This is the other selection statement in C#. Having a switch statement is like having multiple else statements — but based only on one expression. The syntax is as follows —

Advertisment
switch (switch_expression)
{
	case constant-expression:
		statement
		jump-statement

	case constant-expressionN:
		statementN
	
}

Unlike C or C++, there is no support for fall through — which means that a break statement is required after every case statement, except the last (in above case, default) one. But it is possible to combine case statements as follows —

switch (x)
{
	case 1:
		do something;
		break;
	case 2:
	case 3:
case 4:
	do something else;
	break;
default
	...
}

Here is how a switch statement works —
The switch_expression is evaluated and then the result is compared with each constant-expression in the case statements — starting with the first one. When the matching constant-expression is found, the statement in that case is executed. If no match is found and a default is defined, that gets executed. 

Iteration statements:

Iteration statements let you perform controlled iteration or looping. In C# there are 4 statements that can be used for this purpose. 

while

The syntax of while statement is as follows —

while (Boolean Expression)
	embedded-statement

The embedded-statement is executed again and again — till Boolean Expression becomes false. 

do … while

In case of a while statement, what happens when the Boolean expression being evaluated is false to start with? Obviously the embedded-statement inside the while statement is not executed even once. But there are times, when one wants the embedded statement to be evaluated once no matter what the Boolean expression results into. For this we can use the do…while statement, in case of which the Boolean expression is tested at the end of execution cycle. Here is the syntax —

do
    embedded-statement
while ( Boolean-expression )

for

for is the most used iteration statement and the syntax of it is as follows —

for (initialization; Boolean-expression; step)
         embedded-statement

There are 3 parts to the for statement — first part is the initialization and this is done only once. Second part is the Boolean-expression which is evaluated, before every iteration of the loop, to decide whether the execution is to continue or not. Third part is the step — which defines the move of the counter (up or down).
Here is a simple example of the for statement —

using System;

class TestApp
{
    const int FirsttChar = 62;
    const int LastChar = 125;

    static public void Main()
    {
        for (int i = FirstChar; i <= LastChar; i++)
        {
            Console.WriteLine("{0}={1}", i, (char)i);
        }
    }
}

Note that, any or all of these 3 parts can be empty.

 foreach 

foreach is a special statement designed specifically for arrays and collections. Why do we need to have special statement like this for arrays and collections? The reason is that it is very easy for the for statement to go wrong. Some of the situations in which the for statement can be problematic are —

  • If the initialization of the variable is not done correctly
  • If the Boolean expression is not correct
  • If the step is not correct.

Also we should keep in mind that many a times the arrays and collections have
different methods and properties for accessing their count and different
semantics for extracting specific elements.

Using foreach statement we can avoid problems and iterate through arrays and
collections in a uniform manner. Use of foreach statement is quite intuitive and
here is an example —

using System;
using System.Collections;

class MyColorArray
{
    public ArrayList colors;

    public MyColorArray()
    {
        colors = new ArrayList();
        colors.Add("red");
        colors.Add("blue");
        colors.Add("green");
    }
}

class ForeachApp
{
    public static void Main()
    {
        MyColorArray mycArray = new MyColorArray();

        foreach (string color in mycArray.colors)
        {
            Console.WriteLine("{0}", color);
        }
    }
}

Jump statements:

The jump statements are used to jump at a different location in the program
execution from the current one.

break

break is used inside a loop and its use ensures that the control is passed to
statement immediately following the loop.

continue

continue statement too, is used inside a loop. When continue is used, the
current execution is left and execution continues at the beginning of the block.

return

return is different from break and continue. It has 2 functions — it
specifies the value to be returned to the caller and it causes immediate return
to the caller.

We have seen multiple statements in each category and some of the programming
situations do not call for use of one specific one. In such cases, user
preferences, coding guidelines and best practices come into play while deciding
which statements to use.

tech-news