xxxxxxxxxx
var switchValue = 3;
var resultText = switchValue switch
{
1 or 2 or 3 => "one, two, or three",
4 => "four",
5 => "five",
_ => "unknown",
};
xxxxxxxxxx
switch (value)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
xxxxxxxxxx
int number = 4;
switch (number)
{
case 1:
case 2:
case 3:
Console.WriteLine("Small number");
break;
case 4:
case 5:
case 6:
Console.WriteLine("Medium number");
break;
default:
Console.WriteLine("Other");
break;
}
//In this example, the switch statement is evaluating the value of the number variable. If the value is 1, 2, or 3, the code block for the first group of case labels is executed (which prints "Small number" to the console).
//If the value is 4, 5, or 6, the code block for the second group of case labels is executed (which prints "Medium number" to the console), and so on. If the value of the number variable does not match any of the cases,
//the code block for the default case is executed (which prints "Other" to the console).
//To specify multiple case labels for a single code block, you can list the case labels separated by a colon (:) and no code block. The code block for the group of case labels is then specified after the last case label.
//Using multiple case labels can simplify your code and make it easier to read, especially if you have multiple values that should execute the same
xxxxxxxxxx
switch (intVal1, strVal2, boolVal3)
{
case (1, "hello", false):
break;
case (2, "world", false):
break;
case (2, "hello", false):
break;
}
xxxxxxxxxx
int num = 5;
string result;
switch (num)
{
case 1:
result = "Number is 1";
break;
case 2:
result = "Number is 2";
break;
case 3:
case 4:
result = "Number is 3 or 4";
break;
default:
result = "Number is not 1, 2, 3, or 4";
break;
}
Console.WriteLine(result);
xxxxxxxxxx
int x = 2;
int y = 3;
switch (x)
{
case 1:
Console.WriteLine("x is 1");
break;
case 2 when y == 3:
Console.WriteLine("x is 2 and y is 3");
break;
case 2:
Console.WriteLine("x is 2");
break;
default:
Console.WriteLine("x is neither 1 nor 2");
break;
}
xxxxxxxxxx
var value = 5;
var output = value switch
{
1 or 2 or 3 => value + 4,// Do some stuff
4 => value * 3,// Do some different stuff
5 => value / 3,// Do some different stuff
6 => value - 3,// Do some different stuff
_ => value // Default stuff
};