Software Development

Get an overview of C# control statements

Irina Medvinskaya provides an overview of the C# control statements—selection, iteration, and jump—and discusses the appropriate way to use each of them.

In order for developers to utilize any language to the fullest extent, they need to have a complete and thorough understanding of the code flow structures. In this article, I provide an overview of the C# control statements and discuss the appropriate way to use each of them.

Selection statements

If and switch are considered selection statements because they assist in determining the logical path code would take depending on certain conditions. Here's more information about both statements.

The if statement
This statement works with an expression that evaluates to a Boolean value. If the Boolean expression evaluates to true, the statement embedded in the if clause will be executed. If the Boolean expression evaluates to false, the statement in the if clause will not be executed.

The if statement can be followed by an else statement that is executed if the Boolean expression used in the if clause evaluates to false. An else statement can also be used in combination with if. In that instance, it works in a similar way to the ordinary if statement; however, this section of the code is only analyzed if the Boolean expression in the first if clause evaluates to false and the expression in this else if clause evaluates to true.

In general, it's a good practice to utilize the else keyword in order to make sure that all possible scenarios are being handled in the code and can't fall through the cracks in program logic.

Note: When utilizing the if statement to check for equality, you have to use two consecutive equals signs. Two equals signs check for equality, whereas one equals sign simply performs an assignment.

The following is an example of an if statement:

            int i=3;
            if (i == 1)
            {MessageBox.Show("i=1"); }
            elseif (i==2)
            {MessageBox.Show("i=2"); }
            else
            { MessageBox.Show("i=?"); }

The switch statement
This statement evaluates an expression and compares the expression's value to a number of cases. Each case is associated with a statement list that is called a switch section. C# executes a statement list associated with the switch section that matches the expression's value. Switch is an easy-to-read programming alternative to having many if/else pairs whenever you are trying to evaluate a value of a particular expression.

The expression used as the driver for the switch statement is displayed in parentheses that follow the switch keyword. In general, the expression used in the switch statement must evaluate to one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. You can also utilize an expression that can be implicitly converted to one of the above types.

Switch sections start with the keyword case, which is followed by a constant expression. A colon follows the constant expression, and the statement list follows the colon. The break specifies the end of the statement block.

First, C# evaluates the expression in the switch statement. It then looks for a switch block whose expression matches the expression's value. If it can find the matching value in one of the switch sections, the statement list for the switch section executes.

The default keyword in the switch blocks is utilized to execute a particular section of the code whenever none of the cases listed match the value switch block's constant value.

In general, it's a good practice to utilize the default keyword in order to make sure that all possible scenarios are being handled in the code and can't fall through the cracks in program logic.

The following is an example of a switch statement:

            int i=3;
            switch (i)
            {
                case 1:
                    MessageBox.Show("i=1");
                    break;
                case 2:
                    MessageBox.Show("i=2");
                    break;
                default:
                    MessageBox.Show("i=?");
                    break;
            }

Iteration statements

While, do, for, and foreach are considered iteration statements because they assist in executing embedded statements multiple times. Here's more information about the four statements.

The while statement
This statement executes a statement list while an expression evaluates to True. The Boolean expression that controls the while statement is enclosed in parentheses that follow the while keyword. The statements that should be executed while the Boolean expression evaluates to True follow the parentheses.

The following is an example of a while statement:

            int i=3;
           
            while (i < 5 )
            {
            MessageBox.Show(i.ToString());
            i++;
            }

The do statement
This statement executes its embedded statements zero or more times. If the Boolean expression used in the while statement evaluates to false, then none of the embedded statements will be executed. However, in order to ensure that the embedded statements are executed at least once, you can use a do statement.

The do statement is followed by embedded statements, which are followed by a while keyword. The Boolean expression that controls the number of times that the loop executes follows the while keyword. The embedded statements will be executed at least once since the Boolean expression is evaluated after the embedded statements execute.

This is an example of a do statement:

      int i=3;

            do
            {
                MessageBox.Show(i.ToString());
                i++;
            }
            while (i < 3);

The for statement
This statement begins with the for keyword and is followed by parentheses. The parentheses contain an initializer, a condition, and an iterator statement, all separated by semicolons. The embedded statements follow the parentheses.

This is an example of a for statement:

           for (int i=0; i<4; i++)
            {
                MessageBox.Show(i.ToString());
            }
         }

The foreach statement
This statement is used to iterate over the elements in a collection. Since arrays in C# provide support for the foreach statement, you can use the foreach statement to work with each element in the array.

To use the foreach statement, type the foreach keyword, followed by parentheses. The parentheses must contain the following information: the type of the element in the collection; the identifier name for an element in the collection; the keyword in; and the identifier of the collection. Embedded statements follow the parentheses.

This is an example of a foreach statement:

    int[] intArray;
            intArray = newint[3];

            intArray[0] = 0;
            intArray[1] = 1;
            intArray[2] = 2;

            foreach (int ArrayElement in intArray)
                MessageBox.Show(ArrayElement.ToString());

Jump statements

Break, continue, and goto are considered jump statements because they assist in jumping to a specific statement within code. Here's more information about the three statements.

The break statement
This statement is often used in conjunction with switch statements; however, C# allows you to use it to break out of the current block of statements. The break statement is usually used to break out from an iteration statement block.

This is an example of a break statement:

int i = 0;

while (i < 4)
{
MessageBox.Show(i.ToString());
if (i == 2)
break;
i++;
}

The continue statement
This statement returns the control back to the Boolean expression that controls an iteration statement.

This is an example of a continue statement:

for (inti = 1; i <= 4; i++) 

{
if (i < 2)
{
continue;
}
MessageBox.Show (i);
}

The goto statement
This statement transfers control to a labeled statement unconditionally. In C#, any statement can be labeled. A colon follows a statement label, and a label identifier follows the goto keyword. The goto statement transfers control to the statement named by the label identifier.

If you overuse the goto statement, it can create code that is hard to read and follow. In general, it's a good practice to avoid using goto altogether by restructuring the code in a way that allows you to get around using the goto statements.

This is an example of a goto statement:

    int i = 0;
while (i < 3)
{
MessageBox.Show(i.ToString());
if (i == 2)
goto Complete;
i++;
}
Complete: MessageBox.Show("complete");

Additional information

This article contains basic information about the code/flow statements available in C#. If you would like more detailed information about utilizing each statement, visit the Microsoft Web site for details about selection, iteration,and jump statements.

Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a Project Manager at Citigroup.

3 comments
doviddashevsky
doviddashevsky

I just wonder who is audience for this article? I can not see any begginer in C# that would not know about it. May be it done just for VB.NET people who need to read C#?

augie.turano
augie.turano

The syntax is wrong in the IF statements, else if has a space - elseif will yield and error in C#.

Tony Hopkinson
Tony Hopkinson

I wish they'd put total beginner or something on them. However the selection statement does have some wrinkles compared to others. Equally though the compiler will tell you off for implicitly dropping through, and it's easy enough to find out how to explicitly do it. The return of goto wasn't something I was happy about though. FallThrough or Continue would have been better. I fully expect to see some horrible spaghetti code through that particular feature.

Editor's Picks