Switch

C# provides execution control flow, means "if" can decide when which code block to be executed. The first control flow statement is "If-Else" and another control flow statement is switch.

When there are multiple conditions then switch case statement will be used.

Syntax

Try it
switch(expression) 
{
  case somevalue:
    // code block to execute
    break;
  case anothervalue:
    // code block to execute
    break;
  default:
    // If none of the case is matched then this part will be executed
    break;
}

Let's see how switch statement works:

  • The swich statement will accept expression as an argument
  • It will be evaluated only once
  • You can have any number of case statement within a switch statement, each case should be followed by the value and a colon.
  • The value of case must be same data type as the variable we passed into the swich
  • Argument value will be compared with the value of each case one by one
  • Once expression is matched with any case then associated code block will be executed
  • If none of the cases are matched then default case will be executed
  • Once break statement found then it will break the execution flow inside the switch statement and control will immediately moved to the next statement after the switch block.

The break Keyword

Once C# reaches to a break keyword in switch, it breaks the execution and control jumps to the next immediate line after the switch. If no break found in perticular case then it will also execute next case statement.

The default Keyword

It is good idea to have a default case for switch, but it's not compulsory to have it. If we want to execute atleast one code block if no match found then default case will be used. If we omit default case and no match found then switch does nothing.

Example

Try it
using System;

namespace CSharp_Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            int weekday = 3;
            switch (weekday)
            {
                case 1:
                    Console.WriteLine("Day is Monday");
                    break;
                case 2:
                    Console.WriteLine("Day is Tuesday");
                    break;
                case 3:
                    Console.WriteLine("Day is Wednesday");
                    break;
                case 4:
                    Console.WriteLine("Day is Thursday");
                    break;
                case 5:
                    Console.WriteLine("Day is Friday");
                    break;
                case 6:
                    Console.WriteLine("Day is Saturday");
                    break;
                case 7:
                    Console.WriteLine("Day is Sunday");
                    break;
            }
        }
    }
}

Above code will print the output as below

Try it
Day is Wednesday

 

← Previous

Next →