The switch
and case
statements in C# provide a convenient way to execute different code blocks based on the value of a particular expression. The switch
statement allows you to evaluate an expression, and then execute a block of code based on the value of that expression. The case
statement specifies the value that the expression being evaluated by the switch
statement should match in order to execute the code block associated with that case.
Here is an example of how to use the switch
and case
statements in C#:
int num = 2;
switch (num)
{
case 1:
Console.WriteLine("Number is 1");
break;
case 2:
Console.WriteLine("Number is 2");
break;
case 3:
Console.WriteLine("Number is 3");
break;
default:
Console.WriteLine("Number is not 1, 2, or 3");
break;
}
In this example, the value of the num
variable is evaluated by the switch
statement. If the value of num
is 1, the code block associated with the case 1
statement will be executed, and the message "Number is 1" will be printed to the console. If the value of num
is 2, the code block associated with the case 2
statement will be executed, and the message "Number is 2" will be printed to the console. If the value of num
is 3, the code block associated with the case 3
statement will be executed, and the message "Number is 3" will be printed to the console. If the value of num
is none of these values, the code block associated with the default
statement will be executed, and the message "Number is not 1, 2, or 3" will be printed to the console.
One thing to note is that the break
statement is used to exit the switch
statement and prevent the code blocks for any subsequent cases from being executed. If the break
statement is not used, the code blocks for all cases after the matching case will be executed, unless a break
statement is encountered.
Another thing to note is that the switch
statement in C# can only be used with certain types of expressions, including integral types (such as int
and long
), enumerated types, and strings.
In summary, the switch
and case
statements in C# provide a convenient way to execute different code blocks based on the value of a particular expression, and are useful for situations where you need to perform different actions based on a range of possible values.