BlackWasp
C# Programming
.NET 1.1+

C# Program Flow Control: Conditional Processing

The thirty-second part of the C# Fundamentals tutorial concludes the examination of the program flow control commands available within C#. This article considers the conditional processing commands that allow code to be executed when tests are met.

The If Statement

The if statement and structure is the simplest and possibly the most commonly used conditional processing statement. In its simplest format, the statement defines a condition and only executes a piece of code if the condition is met. The syntax of the basic if statement is as follows:

if (condition) command;

The condition section of the if statement defines the condition that must be met. This can be a Boolean variable or an expression that equates to a Boolean value. If the conditional evaluates to true, the command is executed. If false, the command is simply ignored and processing continues with the first command after the if structure. The command may be a single command or a group of commands in a code block surrounded with brace characters { and }.

int toTest = 5;

if (toTest >= 0) Console.WriteLine("Positive");     // Outputs "Positive"
if (toTest < 0) Console.WriteLine("Negative");      // Outputs nothing

The If-Else Statement

Often you will want to execute one piece of code if a condition is met and an alternative section of code if the condition evaluates to false. To achieve this, the if statement structure can be extended by adding an else section using the following syntax:

if (condition) command; else alternative-command;

Using the above syntax, the condition section must still evaluate to a Boolean value. If the Boolean value is true when the if statement is executed, the command statement or code block is executed. If the Boolean value is false, the alternative-command statement or code block is executed. In all cases, one of the two commands will be run but never both.

int toTest = 5;

if (toTest >= 0)
{
    Console.WriteLine("Positive");      // Outputs "Positive"
}
else
{
    Console.WriteLine("Negative");
}

Nested If Statements

As a program increases in complexity, the number of conditions that must be processed may also increase. In some cases it is necessary to nest if statements to achieve the desired results. The nesting may occur in the main body of the if statement, in the else section or within both. When nesting multiple if statements you should consider the indentation of each part to ensure easy readability.

int toTest = 5;

if (toTest >= 0)
{
    if (toTest == 0)
    {
        Console.WriteLine("Zero");
    }
    else
    {
        Console.WriteLine("Positive");  // Outputs "Positive"
    }
}
else
{
    Console.WriteLine("Negative");
}

The "If-Else-If" Ladder

The If-Else-If ladder is a special combination of if-else statements that can be used to test a series of conditions. The first if statement performs a standard Boolean test. If the test is met, the code within the if executes. If not, control passes to the else statement, which contains a second "if" command. This continues as a series of if statements nested within the previous command's else until every condition that requires testing has been checked. A default command or code block may execute when no condition has evaluated to true by adding a final else. The syntax for the if-else-if ladder is as follows:

if (condition 1)
    command 1;
else if (condition 2)
    command 2;
else if (condition 3)
    command 3;
.
.
.
else if (condition X)
    command X;
else
    default command

Using this structure, any number of conditions may be checked and only one condition's associated code will ever be executed. However, the number of checks should not be too high as to make the code difficult to read. Note that although the structure is simply a series of nested if commands, the indentation is minimal to show that a ladder structure is in operation and to improve readability.

The following example shows an if-else-if ladder structure used to categorise a value according to the range that it falls within:

int toTest = 5;

if (toTest < 0)
    Console.WriteLine("Negative");
else if (toTest == 0)
    Console.WriteLine("Zero");
else if (toTest < 5)
    Console.WriteLine("Small");
else if (toTest < 20)
    Console.WriteLine("Medium");        // Outputs "Medium"
else if (toTest < 50)
    Console.WriteLine("Large");
else
    Console.WriteLine("Huge");

The Switch Statement

The second conditional processing structure available in the C# programming language is the switch statement. This statement is similar to the if-else-if ladder as it provides multiple branching. In the case of the switch method, the value of a single variable or expression can be tested against a series of discrete values, or cases, until a match is found. The code within the matched case is then executed. This allows the programmer to choose from multiple actions according to a value.

The switch statement is generally easier to read and more efficient than the if-else-if ladder. However, because it only permits for the testing of a single expression against a list of discrete values, it is not appropriate for all situations. The following shows the general syntax for the switch command:

switch (expression)
{
    case value1:
        commands1;
        break;
    case value2:
        commands2;
        break;
    case value3:
        commands3;
        break;
.
.
.
    default:
        commands;
        break;
}

The first line of the syntax is the switch keyword and the expression that is to be tested. The expression may only evaluate to an integer type, char or string; floating point values and other types cannot be used.

The case elements of the command each define a single value that is to be compared against the original expression. If the value after the case keyword is an exact match for the expression's value then the commands within the case statement are executed. Note that in the switch statement, each case may have several commands and these commands are not enclosed in a code block. Instead, to indicate that the case is complete, a break command is the last statement. This is necessary to ensure that the processing of code does not run into the following case. If the break keyword is missing the code will not compile.

Optionally, a special case can be added at the end of the switch statement. This is the default case. If used, the code within the default case is executed if no match for the expression is found.

The following example shows how the switch command can be used to display a message according to a status code:

string statusCode = "OK";

switch (statusCode)
{
    case "OK":
        Console.WriteLine("Completed.");            // Outputs "Completed"
        break;
    case "Warn":
        Console.WriteLine("Completed with warnings.");
        break;
    case "Err":
        Console.WriteLine("Completed with errors.");
        break;
    case "Fail":
        Console.WriteLine("Failed to complete.");
        break;
    default:
        Console.WriteLine("Unknown status code");
        break;
}

In some situations, you may wish to test the expression for multiple values, each producing the same result. This can be achieved by creating a series of empty cases. When a selected case contains no code, the contents of the next non-empty case statement are used instead. The previous example could be extended to select from multiple status codes with the same results using this method:

string statusCode = "OK";

switch (statusCode)
{
    case "OK":
    case "NoError":
        Console.WriteLine("Completed.");            // Outputs "Completed"
        break;
    case "Warn":
    case "Warning":
    case "Warnings":
        Console.WriteLine("Completed with warnings.");
        break;
    case "Err":
    case "Error":
    case "Errors":
        Console.WriteLine("Completed with errors.");
        break;
    case "Fail":
    case "Failed":
        Console.WriteLine("Failed to complete.");
        break;
    default:
        Console.WriteLine("Unknown status code");
        break;
}
Link to this Page11 March 2007
RSS RSS Feed