C# if, else, switch, ternary Conditional Control Tutorial

In this tutorial we learn how to conditionally control the flow of our application with if, else, else/if and switch statements.

We also cover how to nest if/else and switch statements as well as how to use the shorthand ternary operator (? :).

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is conditional control flow

We can control the flow of our application by evaluating conditions, and executing certain code based on the result.

For example, our application can send a birthday card to an employee if today is their birthday.

The flow of the program changes because the code only executes under certain circumstances.

C# has the following conditional control structures:

  • if else
  • switch

C# also has an operator called the ternary operator, which is an if/else statement wrapped up in an operator.

The if statement

An if statement will test a condition, and execute code if the result of the condition is true.

If our condition is true, whatever is inside the code block will execute. If our condition is false, the next set of code after and outside of the code block will execute.

Syntax:
if(condition)
{
    // code to execute if
    // condition is true
}

// if condition is false
// move onto other code
Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            if (a < 20)
            {
                Console.WriteLine("Condition is true");
            }

            Console.WriteLine("Code after if block");
            Console.ReadLine();
        }
    }
}

In the example above, we check if the value of our variable a is less than “20”. Because a has a value of “10”, the condition will be true and the code inside the code block will execute.

The else statement

The else statement allows us to specify code to execute if our condition evaluates to false.

Syntax:
if(condition)
{
    // code to execute if
    // condition is true
}
else
{
    // code to execute if
    // condition is false
}
Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            if (a > 20)
            {
                Console.WriteLine("Condition is true");
            }
            else
            {
                Console.WriteLine("Condition is false");
            }

            Console.ReadLine();
        }
    }
}

In the example above we test if the value of a is greater than “20”. Because it’s not, the condition evaluates to false, and the code inside the else block executes.

The else/if statement

An else if statement allows us to provide extra test cases with their own execution code.

We can think of an else/if statement as many if statements, one after another.

Syntax:
if(condition)
{
    // code to execute if
    // condition is true
}
else if(condition2)
{
    // code to execute if
    // condition2 is true
}
else
{
    // code to execute if
    // conditions are false
}
Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            if (a > 20)
            {
                Console.WriteLine("Condition 1 is true");
            }
            else if (a >= 10)
            {
                Console.WriteLine("Condition 2 is true");
            }
            else
            {
                Console.WriteLine("Both conditions are false");
            }

            Console.ReadLine();
        }
    }
}

In the example above, the first if test is false. The compiler then moves on to the else/if statement to test its condition. The else/if condition is true and the code inside the else/if execution block executes.

We’re not limited to one else/if statement. We can have as many else/if conditions as we need in one control structure set.

That said, if structures that are too long is a bad practice. In most situations we can refactor our code and simplify the process.

How to nest an if statement

We can nest an if statements inside other if statements. The compiler will evaluate each if in a hierarchical fashion.

All we do is write an if statement inside the execution block of another if statement.

Syntax:
if(checkedFirst)
{
    if(checkedSecond)
    {
        // code to execute
    }
}
Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            if (a < 20)
            {
                Console.WriteLine("outer if");

                if (a >= 10)
                {
                    Console.WriteLine("inner if");
                }
            }

            Console.ReadLine();
        }
    }
}

In the example above, the compiler will start at the outer if statement. If its condition proves true, the compiler will move into the code block where the nested if statement is. The compiler will then test the nested if condition.

We should try not to nest too many statements. A good rule of thumb is that if we nest more than 3 times, we should find a different way to solve the problem.

No curly braces on single statements

When we only have a single execution statement, we don’t have to write the curly braces. Single statements don’t need to be in a code block.

Syntax:
if(condition)
    // execution statement
else if(condition2)
    // execution statement 2
else
    // execution statement 3
Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            if (a < 20)
                Console.WriteLine("Condition 1 is true");
            else if (a >= 10)
                Console.WriteLine("Condition 2 is true");
            else
                Console.WriteLine("Both conditions are false");

            Console.ReadLine();
        }
    }
}

In the example above, each condition only contains a single execution statement, so we don’t write the curly braces.

Certain companies or frameworks may require you to write the curly braces.

This will not work if we have more than one statements. The compiler will raise an error without the curly braces.

Example:
// will not compile
if(a < 20)
    Console.WriteLine("Condition 1 is true");
    Console.WriteLine("a is less than 20");

The if/else ternary operator (?:)

The ternary operator is a shorthand way of writing a if/else statement.

First, we specify a condition, followed by the question mark ( ? ) symbol. Then, we specify a single statement to execute if the condition evaluates to true, followed by a colon ( : ). Finally, we specify a single statement to execute if the condition evaluates to false.

If our condition is true, whatever is after the question mark ( ? ) executes. If our condition is false, whatever is after the colon ( : ) executes.

Syntax:
Condition ? true statement : false statement;

C# requires us to write both a true and false execution statement for the ternary operator. There can only be a single execution statement for each of these.

Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;

            var result = a < b ? true : false;

            Console.WriteLine(result);

            Console.ReadLine();
        }
    }
}

In the example above, we store the result of the operation in a variable for later use. However, we can use the ternary operator directly.

Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;

            Console.WriteLine(a < b ? true : false);

            Console.ReadLine();
        }
    }
}

In the example above, we evaluate the condition and print the result directly.

The switch statement

The switch statement is a different way of writing an else/if statement. We use a switch to evaluate direct comparisons ( x == y).

Before we explain how it works, let’s look at the syntax first.

Syntax:
switch (mainValue)
{
    case checkAgainstValue :
        // if true execute this code
        break;
    default:
        // if none of the cases are true
        break;
}

The switch above would be similar to writing a normal if/else statement.

Example:
if (mainValue == checkAgainstValue)
{
    // if true execute this code
}
else
{
    // if none of the cases are true
}

We have one mainValue that’s checked against multiple cases.

When a case evaluates to true, the execution statements after the colon executes.

The switch statement reads like this: If checkAgainstValue is the same as mainValue, execute the code after the :, then break out of the switch. If none of the cases evaluate to true, execute the code in the default block and break out of the switch.

Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            char grade = 'B';

            switch (grade)
            {
                case 'A':
                    Console.WriteLine("Excellent!");
                    break;
                case 'B':
                    Console.WriteLine("Very good");
                    break;
                case 'C':
                    Console.WriteLine("Well done");
                    break;
                case 'D':
                    Console.WriteLine("You passed");
                    break;
                case 'F':
                    Console.WriteLine("You failed");
                    break;
                default:
                    Console.WriteLine("Invalid grade");
                    break;
            }

            Console.WriteLine("Your grade: {0}", grade);
            Console.ReadLine();
        }
    }
}

In the example above, the switch will do a direct comparison to see if the grade in the variable matches any in the switch.

Let’s see what the example above would look like if we write it in a normal else/if structure.

Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            char grade = 'B';

            if (grade == 'A')
                Console.WriteLine("Excellent!");
            else if (grade == 'B')
                Console.WriteLine("Very good");
            else if (grade == 'C')
                Console.WriteLine("Well done");
            else if (grade == 'D')
                Console.WriteLine("You passed");
            else if (grade == 'F')
                Console.WriteLine("You failed");
            else
                Console.WriteLine("Invalid grade");

            Console.WriteLine("Your grade: {0}", grade);
            Console.ReadLine();
        }
    }
}

The switch statement is an easier and faster way to write direct comparisons.

How to nest a switch statement

Like an if statement, we can nest a switch inside another switch. Once again, the compiler will test the statements hierarchically.

Syntax:
switch (value)
{
    case checkAgainstValue:
        // code to execute
        // and inner switch
        switch (value2)
        {
            case checkAgainstValue2:
                // code to execute 2
                break;
        }

        break;
}

The location of the break of the outer switch is below the inner switch.

Example:
using System;

namespace ControlFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 20;

            switch (a)
            {
                case 10:
                    Console.WriteLine("Outer switch");

                    switch (b)
                    {
                        case 20:
                        Console.WriteLine("Inner switch");
                        break;
                    }
                    break;
            }
            Console.WriteLine("Exact value of a is : {0}", a);
            Console.WriteLine("Exact value of b is : {0}", b);
            Console.ReadLine();
        }
    }
}

As with the nested if/else statement, if we need to nest more than 3 times, we should consider refactoring our code.

Summary: Points to remember

  • An if statement will evaluate a condition and execute code based on the result.
  • An else statement will execute code when an if condition evaluates to false.
  • An else/if statement is used to test multiple if conditions and execute their separate sections of code.
    • If our if, else or else/if control structure only contains one execution statement, we can omit the code block curly braces.
  • We use the ternary operator (? :) as a shorthand method of writing an if/else statement.
  • The switch statement is an easy way to test multiple values against a single main value.
  • We can nest both if and switch statements can inside one another.
  • If we nest more than 3 levels deep, we should consider rewriting the code in a different manner.