C# switch Statement
The C# switch statement selects one block of code from several alternatives. It compares a switch expression with available case labels and executes the first matching section.
A switch statement is often easier to read than a long chain of if, else if, and else conditions when the same value is being compared against several known options.
C# switch Statement Syntax
Following is the syntax of C# switch statement.
switch(match_expression) {
case value1:
statement(s);
break;
case value2:
statement(s);
break;
case valueN:
statement(s);
break;
default:
statement(s);
break;
}
The match_expression is evaluated once. Its result is then compared with the available case labels.
- A
switchstatement may contain one or morecasesections. - Each case label must be unique within the same switch statement.
- The
defaultsection is optional and runs when no other case matches. - A case section must not fall through into the next non-empty case section. It normally ends with
break,return,throw, or another statement that transfers control. - The
defaultlabel may appear anywhere in the switch body, although it is conventionally placed last.
Modern C# switch statements can also match null explicitly, use relational and type patterns, and apply additional conditions with the when keyword.
Example 1: Select a Case Using an Integer
The following program reads an integer and executes the case whose label matches the entered value.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Console.Write("Enter a value [1-3]: ");
int a = Convert.ToInt32(Console.ReadLine());
switch(a){
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
Console.WriteLine("One");
break;
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Enter a value [1-3]: 2
Two
In this run, the user enters 2. The switch expression therefore matches case 2, which prints Two. The following break statement exits the switch.
Notice that the existing case 3 section prints One. A real program would normally print Three there, but the case-selection behavior is still the same.
C# switch with a default Case
Add a default section when the program must handle values that do not match any listed case.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a day number from 1 to 3: ");
int day = Convert.ToInt32(Console.ReadLine());
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("The day number must be between 1 and 3.");
break;
}
}
}
If the user enters 7, none of the numbered cases match, so the default section is executed.
Enter a day number from 1 to 3: 7
The day number must be between 1 and 3.
Group Multiple C# Case Labels
Different case labels can share the same statements by placing the labels together before one code block. This is useful when several values should produce the same result.
using System;
class Program
{
static void Main()
{
char grade = 'B';
switch (grade)
{
case 'A':
case 'B':
Console.WriteLine("Pass with a high grade");
break;
case 'C':
case 'D':
Console.WriteLine("Pass");
break;
case 'F':
Console.WriteLine("Fail");
break;
default:
Console.WriteLine("Unknown grade");
break;
}
}
}
Here, both 'A' and 'B' execute the same statement. This is valid because the labels are different and the first label does not contain its own statements.
Switch with Multiple Cases containing same Matching Value
When you write case statements with a same matching value, you will get a build error.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
Console.Write("Enter a value [1-3]: ");
int a = Convert.ToInt32(Console.ReadLine());
switch(a){
case 1:
Console.WriteLine("One");
break;
case 1:
Console.WriteLine("One");
break;
case 3:
Console.WriteLine("One");
break;
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Program.cs(14,17): error CS0152: The switch statement contains multiple cases with the label value '1' [D:\workspace\csharp\HelloWorld\HelloWorld.csproj]
The build failed. Please fix the build errors and run again.
The compiler reports error CS0152 because the constant label 1 appears twice. Every constant case label in a switch statement must be unique.
This rule is different from grouping cases. Grouping uses distinct labels, such as case 1: and case 2:, followed by one shared statement block.
C# switch with String Values
A switch expression can be a string. String comparisons in case labels are case-sensitive, so "start" and "START" are different values.
using System;
class Program
{
static void Main()
{
string command = "start";
switch (command)
{
case "start":
Console.WriteLine("Starting the service");
break;
case "stop":
Console.WriteLine("Stopping the service");
break;
case null:
Console.WriteLine("No command was provided");
break;
default:
Console.WriteLine("Unknown command");
break;
}
}
}
Use a case null: section when a nullable switch value needs separate handling.
C# switch Pattern Matching with when
Pattern matching allows a case to test a type, a range, or an additional condition. A when guard runs the case only when both the pattern and its condition are satisfied.
using System;
class Program
{
static void Main()
{
int score = 76;
switch (score)
{
case >= 90:
Console.WriteLine("Grade A");
break;
case >= 75:
Console.WriteLine("Grade B");
break;
case >= 60:
Console.WriteLine("Grade C");
break;
default:
Console.WriteLine("Below Grade C");
break;
}
}
}
Cases are checked from top to bottom. Therefore, more specific or higher-range conditions should be placed before broader conditions.
using System;
class Program
{
static void Main()
{
int temperature = 32;
switch (temperature)
{
case int value when value > 35:
Console.WriteLine("Hot");
break;
case int value when value >= 20:
Console.WriteLine("Moderate");
break;
default:
Console.WriteLine("Cool");
break;
}
}
}
C# switch Expression for Returning a Value
A switch expression provides a compact way to calculate and return a value. It uses => between each pattern and its result.
result = expression switch
{
pattern1 => value1,
pattern2 => value2,
_ => defaultValue
};
The underscore pattern _ acts as the fallback and is similar to the default label in a switch statement.
using System;
class Program
{
static void Main()
{
int month = 2;
string season = month switch
{
12 or 1 or 2 => "Winter",
3 or 4 or 5 => "Spring",
6 or 7 or 8 => "Summer",
9 or 10 or 11 => "Autumn",
_ => "Invalid month"
};
Console.WriteLine(season);
}
}
Winter
C# switch Statement versus if-else
| Requirement | Preferred construct |
|---|---|
| Compare one expression with several fixed values | switch statement |
| Return one value from several patterns | Switch expression |
| Evaluate unrelated Boolean conditions | if-else |
| Combine several variables in complex conditions | if-else or pattern matching |
| Handle types, ranges, or structured values | Pattern-based switch |
Choose the form that makes the decision logic easiest to understand. A switch is not automatically better than an if-else chain; it is most useful when the alternatives are based on one expression or a clear set of patterns.
Common C# switch Errors
- Duplicate case labels: Two constant labels cannot contain the same value.
- Missing control transfer: A non-empty case cannot fall through into the next case. End it with
break,return,throw, or another valid transfer statement. - Unreachable patterns: A broad pattern placed before a specific pattern may make the later case unreachable.
- Missing fallback: Without
defaultor_, an unexpected value may receive no handling or cause a non-exhaustive switch expression to fail. - Unexpected string comparison: Constant string cases are case-sensitive.
C# switch Frequently Asked Questions
Is the default case required in a C# switch?
No. The default case is optional in a switch statement. Add it when the program should explicitly handle values that do not match any listed case. A switch expression generally needs a fallback unless its patterns are known to be exhaustive.
Can multiple C# case labels run the same code?
Yes. Place multiple distinct case labels one after another and write the shared statements below the final label. Duplicate labels with the same constant value are not allowed.
Can a C# switch statement use strings?
Yes. A switch statement can match string values, including an explicit null case. Constant string matching is case-sensitive.
What is the difference between a switch statement and a switch expression?
A switch statement executes statement blocks under case labels. A switch expression evaluates patterns and produces a value, making it suitable for assignments, return statements, and concise mappings.
C# switch Tutorial Review Checklist
- Confirm that every constant
caselabel is unique. - Check that each non-empty switch section exits with
break,return,throw, or another valid control transfer. - Place specific range and type patterns before broader patterns.
- Include
default,case null, or_when unmatched input requires handling. - Verify that example output matches the case selected by the supplied input.
TutorialKart.com