C# switch Statement
The switch
statement in C# allows you to test a variable against multiple values and execute different blocks of code depending on the match. It provides a more concise way to write multiple if...else
statements.
Here's the basic syntax of a switch
statement in C#:
switch (variable) { case value1: // code to execute if variable matches value1 break; case value2: // code to execute if variable matches value2 break; // more cases as needed default: // code to execute if variable doesn't match any of the cases break; }
The variable
is the expression that you want to test against the different values. The case
keyword is followed by a value to match against the variable
. If variable
matches a case
value, the corresponding block of code will be executed. The break
keyword is used to exit the switch statement after a case is matched. If no match is found, the default
block will be executed.
Here's an example of using a switch
statement to determine the day of the week:
int dayOfWeek = 4; switch (dayOfWeek) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Invalid day of week"); break; }
In this example, the program tests the value of dayOfWeek
against different cases and prints out the corresponding day of the week. If dayOfWeek
doesn't match any of the cases, the default
block will be executed, printing out an error message.
Note that the switch
statement can also be used with other types of expressions, such as strings and enums, not just integers.