C# switch Case with Example

In C#, switch case is used when we need to execute a particular block of code from multiple blocks of code. Here is the general form of the switch case in C#.

switch(expression)
{
   case 1:
      // block of code to be executed
      // if expression's value is '1'
      break;
   case 2:
      // block of code to be executed
      // if expression's value is '2'
      break;
   .
   .
   .
   case N:
      // block of code to be executed
      // if expression's value is 'N'
      break;
   default:
      // block of code to be executed
      // if no cases matches the expression
      break;
}

The break statement is used to stop the remaining execution of the switch block or it is used to break out from the switch block. We will discuss about it later in this C# tutorial series. And the default case is used when we need to execute some block of code, in case all specified cases are mismatched. Now let me create an example on switch case in C#:

Console.Write("Today is ");

switch((int) System.DateTime.Now.DayOfWeek)
{
    case 1:
        Console.Write("Monday");
        break;
    case 2:
        Console.Write("Tuesday");
        break;
    case 3:
        Console.Write("Wednesday");
        break;
    case 4:
        Console.Write("Thursday");
        break;
    case 5:
        Console.Write("Friday");
        break;
    case 6:
        Console.Write("Saturday");
        break;
    case 7:
        Console.Write("Sunday");
        break;
    default:
        Console.Write("Something went wrong!");
        break;
}

Since I am writing this blog on Thursday, today is Thursday. Therefore, the output produced by this C# example should be:

Today is Thursday

since the code (int) System.DateTime.Now.DayOfWeek will return 4, which matches the fourth case, that is, case 4, therefore, the block of code written in that case will be executed..

C# Online Test


« Previous Tutorial Next Tutorial »