Switch statements in C#

This tutorial explains how to write switch statements in C# language. Switch statements are used to select one from many different blocks of code. A switch statement can take a variable and check if its value matches one of many different specified values. Once the switch statement finds a matching case, it will run the code inside that case and the stop testing all the other cases.

Watch the video below and then scroll down to the sample code to see how switch statements work.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int myNumber = 5;
      switch (myNumber) {
        case 1:
          Console.WriteLine("The number is 1");
          break;
        case 2:
          Console.WriteLine("The number is 2");
          break;
        case 3:
          Console.WriteLine("The number is 3");
          break;
        default:
          Console.WriteLine("I don't know this number");
          break;
      }
    }
  }
}

Next tutorial: While loops in C#