Switch statements in C#

We have looked at how to use if statements for conditional programming in C#. However, there is something else we can use if there are many different conditions or cases we want to test. We can use switch statements. Switch statements can contain a number of ‘cases’ and a ‘default’ if none of the specified cases are chosen or met.

Have a look at the sample code below. In this program, the user is asked to enter a number between 1 and 5. Based on the number the user enters, they will be presented with an interesting fact about that number. Each number is a different case and there is also ‘default’ case that will be used if the user does not enter one of those 5 numbers.

Each case also uses a ‘break’ so that if a case is met, then the other cases will not also be checked. In other words, the switch statement will end as soon as a case is met. Here is the sample code:

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      // Ask the user to enter a number between 1 and 5
      Console.WriteLine ("Enter a number between 1 and 5 for an interesting fact:");
      int number = int.Parse( Console.ReadLine ());

      switch (number) {
      case 1:
        Console.WriteLine ("1 is the number of websites that existed in 1991.");
        break;
      case 2:
        Console.WriteLine ("2 is the only even prime number.");
        break;
      case 3:
        Console.WriteLine ("3 is the number of days you can survive without water (on average).");
        break;
      case 4:
        Console.WriteLine ("4 is the number of miles per second that space junk moves around Earth.");
        break;
      case 5:
        Console.WriteLine ("5 is the length in meters of a Great White Shark.");
        break;
      default:
        Console.WriteLine ("You did not select a valid option.");
        break;
      }

      Console.ReadLine ();
    }
  }
}

Here is an example of what the user will see when they enter the number 4…

switch_cs_example

Note: When copying the code, only copy the actual code you need. The code above uses a namespace that may be different to the name of your project or solution. If you copy all of the code above and replace all of your code with it, then make sure you change the namespace name above to match the one in your project.