The case
statement is used as part of the switch
statement to define specific values or ranges that are matched against the value of the variable being evaluated. It allows the program to execute different code blocks based on the value of the variable.
Here's how you can use the case
statement:
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 switch
statement evaluates the value of the variable num
. Depending on its value, the program will execute the corresponding case
block. If num
is 2, the output will be "Number is 2".
case
statement:Each case
block must end with a break
statement to prevent fall-through to the next case. Without the break
, execution will continue to the next case
block, even if the value does not match, until it finds a break
or reaches the end of the switch
statement.
The default
label is optional and provides a block of code that executes when none of the case
conditions match the value of the variable.
The value in a case
label must be a constant expression, such as a literal or constant variable. It cannot be a variable or non-constant expression.
The case
statement is a powerful tool for performing multiple checks on the same variable, making code more concise and readable when multiple conditions need to be evaluated. It is commonly used when there are a fixed number of possible outcomes based on the value of a variable.