C# switch

There’s a value in a variable and you don’t know what that value is but you have multiple guesses about what the value might be. Also for each value you have a block of code ready to be executed.

This scenario is a perfect candidate for the use of the switch statement!

Basically the switch statement takes an input. Within the body of this statement we can define different values and a block of code for each of these values. Now the input is compared with the already defined values in the body of the switch statement. At the end, the body of any value that matches the input is the one to be executed.

For example someone asked us to write a program that checks an integer value; if that value is 1, we need to send the “Hello” message to the output stream. If the value is 2 we need to send the “Good Morning” message to the output stream, and if the value is 3 then we should send the “Good Bye” message to the output stream.

This is basically a situation where we can use the switch statement.

Before writing the program, let’s go and see the structure of a switch statement:

switch (expression){
case value1:
//body…
case value2:
//body…
case value_N:
//body…
default:
//body…
}

switch: to create a switch statement, we start with the keyword switch.

( ): after the keyword switch comes the parentheses () and inside it we set the input value that we want to check.

`{ }`: the opening and closing braces declare the body of the switch statement.

case: each case statement is a checkpoint where we put a value. This value then will be checked against the input (that is set within the parentheses of the switch statement) and if they matched, the body of that case statement will run.

Also the body of a case statement starts after the colon : and ends right before the next case statement or the default statement.

Notes:

  1. Depending on the design of the switch statement, we can put one
    or more `case` statement.

  2. Within the body of each `case` statement we need to use either
    `break` or ` return` statement to end the execution of the
    body of the `switch ` statement and jump out.

If we use the break statement, the CPU will run the instructions after the body of the switch statement (it means still in the same method that the switch statement is).

But if we use the return statement instead, that means return from not just the body of the switch statement but also from the method that this statement is in.

Note: in later sections we explained more about break and return keywords.

default: the use of default statement is like using else statement in the if-else. The body of this statement will only run if none of the case statements match the input value.

Example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
int iVal = 3;

switch (iVal)

{

case 1:

Console.WriteLine("Hello");
break;

case 2:

Console.WriteLine("Good Morning");
break;

case 3:

Console.WriteLine("Good Bye");
break;

default:

Console.WriteLine("unknown value");
break;
}
}
}
}

Output:

Good Bye

In this example, we used the value of the iVal variable as the input value of the switch statement.

Within the body of this statement, we first started with the case 1 and here the value of this case statement will be checked against the input value. But because these two values are not equal, the body of this statement will be ignored and the next case statement is the one to be checked next.

The second case statement also has the value 2 and is not a match for the input value, and so this statement is also rejected.

The third case statement has the value 3 and it is actually equal with the input value. So the body of this statement will run.

Then inside the body of this third statement, we sent the message “Good Bye” to the output stream and after that, we called the break statement to break the body of the switch statement and move on to those instructions after this body.

Note: for this particular example, there’s no instruction after the body of the switch statement and so after the call to the break statement, the main method reaches the end of its instructions and so terminates.

Also as you can see the body of the default statement in the example above didn’t run because the third case statement matched the input value and so there’s no need to run the body of the default.

Note: we can also put multiple case statements under each other and define only one body for them.

Example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
int value = 3;

switch (value)

{

case 1:

case 2:

case 3:

Console.WriteLine(" The input value is in range of 1-3 inclusive ");
break;

case 4:

case 5:

case 6:

Console.WriteLine(" The input value is in range of 4-6 inclusive ");
break;

default:

Console.WriteLine("The range of the input value is unknown");
break;
}
}
}
}

Output: The input value is in range of 1-3 inclusive

In this example the first 3 case statements have one body and any of these cases that matches the input, will run this body. Also the last 3 case statements have only one body.

Note: the body of each case as well as default block needs to have one either return; or break; statement otherwise you’ll get a compile time error.

Prior to C# 7, match expressions in switch statements were limited to comparing a variable to constant values, sometimes referred to as the constant pattern. In C# 7, switch statements can also employ the type pattern, where case statements can evaluate the type of the variable being checked and case expressions are no longer limited to constant values.

Note: the rule that each case statement must be terminated with a return or break still applies.

Example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
object name = Console.ReadLine();

switch (name)

{

case int i:

Console.WriteLine($"The type is int and the value is: {i}");
break;

case string s:

Console.WriteLine($"The type is string and the value is: {s}");
break;
}
}
}
}

When the program is running, it will ask you to enter a value. For the sake of this example, enter a name for example John and hit enter. After that you’ll see the body of the second case block will execute and the message below will appear on the console:

The type is string and the value is: John

A couple of notes about this example:

  • The `ReadLine()` method is used to read the user’s input from the
    console. For example if you enter a number, it will read that and return
    it back to the program. So here we’ve set a variable of type object
    (explained in a moment) and for its value we’re going to take the user’s
    input.

  • Because we didn’t get into the concepts of class and objects yet,
    it’s a little bit difficult to get into details of the `object` data
    type yet. But for now just remember that this is another data type and
    it can store any type of data in a program. For example we can store a
    value of type float, int, string etc. in a variable of type
    `object`.

  • If you rerun the example above and this time put another value of
    type `int`, the first `case` statement will run instead because the data
    type matches the first case statement.

In short: in this example the first case statement is saying if the input value is of type int, then assign the value into the variable i and run the body of this case statement. On the other hand, the second case statement is saying if the data type of the input value to the switch is string then assign that value into the variable s and run the body of this case statement.

Of course we can use the created variables in the body of their cases.

In addition to evaluating on the type of the match expression, when clauses can be added to the case statements to evaluate conditions on the variable.

Example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
object name = Console.ReadLine();

switch (name)

{
case int i when i==10:
Console.WriteLine($"The type is int and the value is 10");
break;
case int i when i == 20:
Console.WriteLine($"The type is int and the value is 20");
break;

case string s:

Console.WriteLine($"The type is int and the value is: {s}");
break;

default:

Console.WriteLine("Unknown value");
break;
}
}
}
}

Output:

This time we use the when clause to add condition to the first two case statements. Basically for the first case statement we’ve set that if the input to the switch is of type int and also the value is equal to 10, then run the body of this case statement. So remember both conditions are now checked and both should return true for the body to be run.

Also in the second case statement, we’ve declared that if only the type is int and the value is 20 run the body of this statement.

So as you can see, via the when clause we can add more condition to the case statement.