In C#, the switch statement serves as a control structure that enables the execution of distinct code blocks based on the value of a variable. It is frequently utilized when there is a need to compare a variable with multiple constant values and to carry out various actions according to the outcome.
Basic Syntax of switch in C#
switch (expression)
{
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
case value3:
// Code block for value3
break;
default:
// Code block if no case matches
break;
}
- expression: The value or variable you want to check.
- case: Each case label contains a constant value to compare with the expression.
- break: Terminates the switch block. Without a break, the program "falls through" to the next case.
- default: This is optional and is executed if none of the case labels match the expression.
Example 1. A basic example of a switch case with int.
When the parameter inputValue is set to 2.
public void UseOfSingleWithIntTypeSwitchCase(int inputValue)
{
switch (inputValue)
{
case 1:
Console.WriteLine("Input Value is 1");
break;
case 2:
Console.WriteLine("Input Value is 2");
break;
case 3:
Console.WriteLine("Input Value is 3");
break;
default:
Console.WriteLine("Input Value is something else");
break;
}
}

Output is Input value is 2.
Example 2. Example of switch case with string.
When the parameter inputValue is set to "green".
public void UseOfSingleWithStringTypeSwitchCase(string inputColorValue)
{
switch (inputColorValue)
{
case "red":
Console.WriteLine("The color is red");
break;
case "blue":
Console.WriteLine("The color is blue");
break;
case "green":
Console.WriteLine("The color is green");
break;
default:
Console.WriteLine("Unknown color");
break;
}
}

Output. The color is green.
Example 3. Multiple Cases in One Block (Fall-Through)
When the parameter inputValue is set to 'C'.
public void UseOfMultipleSwitchCase(char inputValue)
{
switch (inputValue)
{
case 'A':
case 'B':
case 'C':
Console.WriteLine("You passed!");
break;
case 'D':
case 'F':
Console.WriteLine("You failed.");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
}

Output. You passed!
Example 4. Switch with when Clause (C# 7.0+)
The introduction of pattern matching in C# 7.0, facilitated by the when keyword, enables the incorporation of more intricate conditions within the switch statement.
When the parameter inputValue is set to 5.
public void UseOfSingleWithWhenClauseSwitchCase(int inputValue)
{
switch (inputValue)
{
case int n when (n >= 1 && n <= 10):
Console.WriteLine("inputValue is between 1 and 10");
break;
case int n when (n > 10):
Console.WriteLine("inputValue is greater than 10");
break;
default:
Console.WriteLine("inputValue is less than 1");
break;
}
}




Join the conversation! Your thoughts help the community grow.