In C#, the switch
statement is used to evaluate an expression and execute different blocks of code based on the value of that expression. It provides a way to simplify multiple if-else
statements when checking for different conditions.
Here’s the basic syntax of a switch
statement in C#:
switch (expression) { case value1: // Code block to be executed if expression matches value1 break; case value2: // Code block to be executed if expression matches value2 break; // Add more cases as needed default: // Code block to be executed if expression doesn't match any cases break; }
Here’s a breakdown of the different parts of a switch
statement:
expression
is the value that is being evaluated.case value1
is a specific value that is compared to the expression.// Code block
refers to the block of code that is executed if the expression matches the specified value.break
is used to exit theswitch
statement once a match is found. Without it, the execution would continue to the next case.default
is an optional case that is executed if the expression doesn’t match any of the specified cases. It’s similar to theelse
part of anif-else
statement.
Here’s an example to illustrate the usage of switch
:
int num = 2; switch (num) { case 1: Console.WriteLine("The number is 1"); break; case 2: Console.WriteLine("The number is 2"); break; case 3: Console.WriteLine("The number is 3"); break; default: Console.WriteLine("The number is not 1, 2, or 3"); break; }
In this example, if the value of num
is 2, the output will be “The number is 2” because it matches the case 2
condition.