switch-case statement in C# full Explanation

In C#, the switch statement provides a convenient way to execute Different blocks of code based on the value of a variable or an expression. It is often used as an alternative to multiple if-else statements when comparing a single value against multiple cases. Here's a full explanation of the switch-case statement in C#:

 

Syntax:

The syntax for a switch-case statement in C# is as follows:

 

 

switch (expression)

{

case value1:

// code block executed when expression matches value1

break;

case value2:

// code block executed when expression matches value2

break;

// more cases...

default:

// code block executed when expression doesn't match any case

break;

}

 

 

Explanation:

v  The `expression` is evaluated, and its value is compared against the values specified in each case.

v  The `case` keyword is followed by a constant value or an expression that the `expression` is compared against.

v  When a match is found, the corresponding code block is executed until the `break` statement is encountered or the end of the switch statement is reached.

v  The `break` statement is used to exit the switch statement and prevent the execution of subsequent cases. If omitted, the execution will continue to the next case.

v  If none of the cases match the `expression`, the code block under the `default` label (if provided) is executed.

v  The `default` label is optional and serves as the "catch-all" case when no other cases match. It is usually placed at the end of the switch statement.

 

Example:

Here's an example to demonstrate the usage of switch-case in C#:

int day = 3;

string dayName;

 

switch (day)

{

    case 1:

        dayName = "Monday";

        break;

    case 2:

        dayName = "Tuesday";

        break;

    case 3:

        dayName = "Wednesday";

        break;

    case 4:

        dayName = "Thursday";

        break;

    case 5:

        dayName = "Friday";

        break;

    case 6:

        dayName = "Saturday";

        break;

    case 7:

        dayName = "Sunday";

        break;

    default:

        dayName = "Invalid day";

        break;

}

 

Console.WriteLine("Today is " + dayName);

 

 

In this example, the value of the `day` variable is compared against Different cases using the switch statement. Based on the match, the corresponding `dayName` is assigned. If none of the cases match, the default case is executed, which assigns "Invalid day" to `dayName`. Finally, the result is printed using `Console.WriteLine`.

 

The switch-case statement provides an efficient and readable way to handle multiple cases in C# and can be particularly useful when there are many possible values to compare against. It improves the clarity and maintainability of your code by organizing it into distinct cases.