c-sharp
  1. c-sharp-switch

C# Switch Statement

Syntax

switch (expression)
{
    case value1:
        // Statements
        break;
    case value2:
        // Statements
        break;
    ...
    default:
        // Statements
        break;
}

Example

string dayOfWeek = "Saturday";

switch (dayOfWeek)
{
    case "Monday":
        Console.WriteLine("Today is Monday.");
        break;
    case "Tuesday":
        Console.WriteLine("Today is Tuesday.");
        break;
    case "Wednesday":
        Console.WriteLine("Today is Wednesday.");
        break;
    case "Thursday":
        Console.WriteLine("Today is Thursday.");
        break;
    case "Friday":
        Console.WriteLine("Today is Friday.");
        break;
    case "Saturday":
        Console.WriteLine("Today is Saturday.");
        break;
    case "Sunday":
        Console.WriteLine("Today is Sunday.");
        break;
    default:
        Console.WriteLine("Invalid day.");
        break;
}

Output

Today is Saturday.

Explanation

The switch statement provides a way to execute different code blocks depending on the value of a given expression. The expression is evaluated once, and then the value is compared to each case label in the switch block.

If a case label matches the value of the expression, the code block following the case label is executed until a break statement or the end of the switch block is reached. If none of the case labels match the value of the expression, the code block following the default label is executed.

The break statement is used to exit the switch block and prevent the execution of other code blocks. If there is no break statement after a case label, the code block of the next case label will be executed until a break statement is encountered.

Use

The switch statement is used when we need to execute different code blocks based on the value of a given expression. It is an alternative to using multiple if-else statements, which can be cumbersome and hard to read, especially when dealing with many different conditions.

Important Points

  • The switch statement provides a way to execute different code blocks based on the value of an expression.
  • The expression is evaluated once, and then compared to each case label in the switch block.
  • The break statement is used to exit the switch block and prevent the execution of other code blocks.
  • If there is no break statement after a case label, the code block of the next case label will be executed until a break statement is encountered.

Summary

The switch statement provides an easy and concise way to execute different code blocks based on the value of a given expression. It is a useful tool when dealing with many different conditions and can make our code more readable and manageable than using multiple if-else statements.

Published on: