TOC

The community is working on translating this tutorial into Afrikaans, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Control Structures:

The switch statement

The switch statement is like a set of if statements. It's a list of possibilities, with an action for each possibility, and an optional default action, in case nothing else evaluates to true. A simple switch statement looks like this:

int number = 1;
switch(number)
{
    case 0:
Console.WriteLine("The number is zero!");
break;
    case 1:
Console.WriteLine("The number is one!");
break;
}

The identifier to check is put after the switch keyword, and then there's the list of case statements, where we check the identifier against a given value. You will notice that we have a break statement at the end of each case. C# simply requires that we leave the block before it ends. In case you were writing a function, you could use a return statement instead of the break statement.

In this case, we use an integer, but it could be a string too, or any other simple type. Also, you can specify the same action for multiple cases. We will do that in the next example too, where we take a piece of input from the user and use it in our switch statement:

Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
    case "yes":
    case "maybe":
Console.WriteLine("Great!");
break;
    case "no":
Console.WriteLine("Too bad!");
break;
}

In this example, we ask the user a question, and suggest that they enter either yes, no or maybe. We then read the user input, and create a switch statement for it. To help the user, we convert the input to lowercase before we check it against our lowercase strings, so that there is no difference between lowercase and uppercase letters.

Still, the user might make a typo or try writing something completely different, and in that case, no output will be generated by this specific switch statement. Enter the default keyword!

Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
    case "yes":
    case "maybe":
Console.WriteLine("Great!");
break;
    case "no":
Console.WriteLine("Too bad!");
break;
    default:
Console.WriteLine("I'm sorry, I don't understand that!");
break;
}

If none of the case statements has evaluated to true, then the default statement, if any, will be executed. It is optional, as we saw in the previous examples.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!