Decisions and Branching

Changing the flow of control in a program in response to some kind of input or calculated value is an essential part of a programming language. C# provides the ability to change the flow of control, either unconditionally, by jumping to a new location in the code, or conditionally, by performing a test.

Remarks

The simplest form of conditional branching uses the if construct. You can use an else clause with the if construct, and if constructs can be nested.

using System;

class Program
{
    static void Main()
    {
        int x = 1;
        int y = 1;


        if (x == 1)
            Console.WriteLine("x == 1");
        else
            Console.WriteLine("x != 1");


        if (x == 1)
        {
            if (y == 2)
            {
                Console.WriteLine("x == 1 and y == 2");
            }
            else
            {
                Console.WriteLine("x == 1 and y != 2");
            }
        }                
    }
}

Note

Unlike C and C++, if statements require Boolean values. For example, it is not permissible to have a statement that doesn't get evaluated to a simple True or False, such as (a=10). In C#, 0 cannot be substituted for False and 1, or any other value, for True.

The statements following the if and else keywords can be single lines of code as shown in the first if-else statement in the previous code example, or a block of statements contained in braces as shown in the second if-else statement. It is permissible to nest if-else statements, but it is usually considered better programming practice to use a switch statement instead.

A switch statement can perform multiple actions depending on the value of a given expression. The code between the case statement and the break keyword is executed if the condition is met. If you want the flow of control to continue to another case statement, use the goto keyword.

using System;

class Program
{
    static void Main()
    {
        int x = 3;

        switch (x)
        {
            case 1: 
                Console.WriteLine("x is equal to 1");
                break;

            case 2:
                Console.WriteLine("x is equal to 2");
                break;

            case 3:
                goto default;

            default:
                Console.WriteLine("x is equal to neither 1 nor 2");
                break;
        }
    }
}

The expression that the switch statement uses to determine the case to execute must use the Built-in Data Types, such as int or string; you cannot use more complex user-defined types.

Unlike Visual Basic, in C# the condition must be a constant value. For example, it is not permissible to compare the expression to a range of values.

See Also

Concepts

C# Language Primer

Reference

Selection Statements (C# Reference)

Jump Statements (C# Reference)