Switch Statement

C#Today, we will talk about Switch statement.  There is nothing new in this statement.  If you are from any programming background, then you may have an idea what this statement actually do.  But for the people, who are not from the programming background, I give you a little bit idea what this statement actually do.  Switch statement takes a variable, whose value you want to check and perform a switch according to that.  To perform a switch, we make use of case keyword inside Switch statment scope.  A code example has been given below.

using System;

namespace MyHelloWorld
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please Enter a Number: ");
            string number = Console.ReadLine();

            switch (number)
            {
                case "1":
                    Console.WriteLine("The number is 1.");
                    break;

                case "2":
                    Console.WriteLine("The number is 2.");
                    break;

                default:
                    Console.WriteLine("The number is not 1 or 2.");
                    break;
            }
        }
    }
}

In this code, we are basically asking a user to enter a number either 1 or 2.  Then, using Console.Readline() method, we are reading the entered value by the user and storing that into a number variable.

Now, our number variable got the value and we want to check whether it is 1 or 2.   For that, we are using Switch statement and using case keyword to check the value of number variable.   If that matches the value, the code after case 1 or 2 will be executed .  If not, the code after default keyword will be executed.   We are making use of break keyword just to get out of further checking process.   Because there is no point of performing more checks, when you already found a match.

This code works very much similar to if and else statement.  It depend upon your choice, which one you want to use.