Tech

How to Use a Switch Statement in C#


Tidy up awkward repeated if statements with the convenient language feature.


In an application, it is common for certain events to only occur based on certain conditions. You can use different types of conditional statements to handle these events. This includes if-statements, if-else statements, switch statements, and more.


Switch statements can be a clean way to organize a set of conditions. This is especially true if you do not want to use a chain of several if-statements, or if you are comparing the value of one particular variable.

You can create switch statements in many programming languages, including C#.


How to Add Different Cases to the Switch Statement

Most languages, including Python, C, and JavaScript, use a variety of conditional statements. It’s important to understand how each statement works, and when it’s most appropriate to use.

Switch statements contain several different “cases”. The switch statement selects a specific value, which it then compares to specific cases. This allows you to determine which section of code the program should execute.

In C#, you can practice writing a switch statement in a simple C# console application.

  1. Create a new C# console application. Open Visual Studio and select Create a new project.
    New project menu in Visual Studio

  2. Choose Console Application, and click on Next.
    New console application selection in Visual Studio

  3. Name your project and choose where you want to store it. Click on Next.
    Configure your new project screen in Visual Studio

  4. Keep the default target framework, and click Create. Your C# application will open a default Hello World program.
  5. Replace the current “Hello World” printout statement in the Main() function. Instead, ask the user to choose from a list of options. Prompt the user to enter their choice into the console application:

    Console.WriteLine("Choose an option:");
    Console.WriteLine("1. Fruit");
    Console.WriteLine("2. Mains");
    Console.WriteLine("3. Desserts");
    Console.WriteLine("");


    Console.Write(">> ");
    string meals = Console.ReadLine().ToLower();

  6. Add a switch statement to print out a different message to the user, depending on what they type into the console. Enter the user’s input (the meals variable) into the switch statement.
    switch (meals)
    {
    }
  7. Inside the switch statement, add cases for each of the possible options the user can select. For each option, add different print statements. If the user’s input matches a case, the particular code for that case will execute. The break keyword forces the program to exit out of the switch statement, and to start executing the code that follows outside of it.
    switch (meals)
    {
    case "fruit":
    Console.WriteLine("Fruits include apples, oranges, and bananas.");
    break;

    case "mains":
    Console.WriteLine("Mains include steak, salmon, or risotto.");
    break;

    case "desserts":
    Console.WriteLine("Desserts include chocolate cake, apple pie, or ice cream.");
    break;
    }

  8. Click on the green play button at the top of the Visual Studio window to run the program.
    Runtime button in Visual Studio

  9. Enter the word “Fruit”, “Mains” or “Desserts”. The statement printed will be different depending on what string you enter into the console app.
    Console with dessert option selected

Switch Statements Using Numbers

Instead of the user entering a string such as “Fruit”, they can also enter the corresponding number instead, such as “1”. For this to work, you can use numbers as options for your switch statement.

  1. Before the switch statement, validate that the user’s input is a number. This is because even if the user enters a number into the console, the program will still store it as a string. If you do not validate this, you may receive a compilation error or an exception when running the application. You will then need to debug this using Visual Studio.
    int result = 1;

    try
    {
    result = Int32.Parse(meals);
    }
    catch (FormatException)
    {
    Console.WriteLine($"'{meals}' is an invalid format. Please enter a number.");
    System.Environment.Exit(1);
    }

  2. Replace the current switch statement. Instead of using strings for the case options, use numbers. In this case, if the user types “1”, the program will run the code from the first case.
    switch (result)
    {
    case 1:
    Console.WriteLine("You selected option 1 (Fruit), which includes apples, oranges, and bananas.");
    break;

    case 2:
    Console.WriteLine("You selected option 2 (Mains), which includes steak, salmon, or risotto.");
    break;

    case 3:
    Console.WriteLine("You selected option 3 (Desserts), which includes chocolate cake, apple pie or ice cream.");
    break;
    }

  3. Click on the green play button at the top of the Visual Studio window to run the program.
    Runtime button in Visual Studio

  4. In the console app, enter a number that corresponds with one of the options, such as “1”, “2”, or “3”. The output will differ depending on what number you enter into the console.
    Console with fruit option selected

How to Add a Default Case to the Switch Statement

The user may also enter a number that is not part of the available list of options, such as “4”. If this happens, the switch statement will still run against that value. However, since it does not match any of the cases, none of the code will execute. You can add a default case for every other option that might occur.

  1. Replace the switch statement with a new one that includes a default case at the bottom:
    switch (result)
    {
    case 1:
    Console.WriteLine("You selected option 1 (Fruit), which includes apples, oranges, and bananas.");
    break;

    case 2:
    Console.WriteLine("You selected option 2 (Mains), which includes steak, salmon, or risotto.");
    break;

    case 3:
    Console.WriteLine("You selected option 3 (Desserts), which includes chocolate cake, apple pie or ice cream.");
    break;


    default:
    Console.WriteLine("The number you entered is not part of the available options.");
    break;
    }

  2. Click on the green play button at the top of the Visual Studio window to run the program.
    Runtime button in Visual Studio

  3. In the console app, enter a number that is outside the range of options, such as “4”, to receive the output from the default case.
    Console with default case selected

Using Switch Statements in Your Application

You can use the switch statement in C# to organize code that will only run under certain conditions. Using switch is often a cleaner and more reliable alternative to a series of if statements.

Other programming concepts that you can look into include classes or structures. These are also important programming concepts that you can use to keep your code well organized.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button