C# switch statement
The switch
statement in C# is a control flow statement that allows you to select one of many code blocks to execute, based on the value of a variable or expression. It's a more readable alternative to using multiple if-else if
statements when you need to compare a single variable against several possible values.
1. Syntax of switch
Statement
switch (expression)
{
case value1:
// Code block to execute if expression equals value1
break;
case value2:
// Code block to execute if expression equals value2
break;
// You can add more cases as needed
default:
// Code block to execute if none of the cases match
break;
}
Key Parts:
expression
: The value or variable being evaluated (must be of a primitive type, enum, or string).case value1
,case value2
, ...: These define the specific values thatexpression
is compared against. Each case is followed by a block of code to execute if the case matches.break
: Terminates theswitch
statement to prevent fall-through to the next case.default
: An optional block that executes if none of the specifiedcase
values match the expression. Think of it as the equivalent of theelse
in anif-else
statement.
2. Example of a Simple switch
Statement
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
default:
Console.WriteLine("Weekend");
break;
}
Explanation:
- In this example,
day
is evaluated. - If
day
equals1
, it prints"Monday"
, and then thebreak
statement terminates theswitch
. - If
day
equals2
, it prints"Tuesday"
, and so on. - If
day
doesn’t match any of thecase
values, thedefault
block is executed, printing"Weekend"
.
3. Why Use switch
Instead of if-else
?
- Readability: When you need to check a single variable against multiple specific values,
switch
statements make your code more organized and easier to read compared to multipleif-else if
conditions. - Performance: In some cases, the
switch
statement can be more efficient than anif-else if
chain, especially when dealing with many possible values.
4. Example with Strings in switch
You can also use strings in a switch
statement:
string fruit = "Apple";
switch (fruit)
{
case "Apple":
Console.WriteLine("You chose Apple.");
break;
case "Banana":
Console.WriteLine("You chose Banana.");
break;
case "Orange":
Console.WriteLine("You chose Orange.");
break;
default:
Console.WriteLine("Unknown fruit.");
break;
}
Explanation:
- The value of
fruit
is compared with eachcase
. If it matches"Apple"
, the code prints"You chose Apple."
and then breaks. - If the
fruit
doesn’t match any case, thedefault
block runs, printing"Unknown fruit."
5. Fall-Through in switch
Statement
In C#, switch
statements do not allow implicit fall-through between cases, meaning each case
must end with a break
, return
, or another terminating statement.
However, you can explicitly group cases if you want multiple cases to execute the same code:
int number = 2;
switch (number)
{
case 1:
case 2:
case 3:
Console.WriteLine("The number is between 1 and 3.");
break;
case 4:
case 5:
Console.WriteLine("The number is either 4 or 5.");
break;
default:
Console.WriteLine("The number is outside the range.");
break;
}
Explanation:
- In this example,
case 1
,case 2
, andcase 3
are grouped to execute the same block of code if the number is between 1 and 3.
6. Example with Enums
switch
statements work well with enums. Enums represent a set of named constants and can make your code more readable:
enum Day
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Day today = Day.Tuesday;
switch (today)
{
case Day.Monday:
Console.WriteLine("Today is Monday.");
break;
case Day.Tuesday:
Console.WriteLine("Today is Tuesday.");
break;
case Day.Wednesday:
Console.WriteLine("Today is Wednesday.");
break;
default:
Console.WriteLine("It's a weekend!");
break;
}
Explanation:
- Here,
today
is an enum value of typeDay
. - The
switch
statement checks the day and prints the corresponding message. - This is useful for making your code more readable and less prone to errors.
7. Using switch
with Ranges (C# 8.0 and above)
Starting with C# 8.0, you can use pattern matching in switch
statements to handle more complex conditions, including ranges:
int grade = 85;
switch (grade)
{
case int g when g >= 90:
Console.WriteLine("A");
break;
case int g when g >= 80:
Console.WriteLine("B");
break;
case int g when g >= 70:
Console.WriteLine("C");
break;
default:
Console.WriteLine("F");
break;
}
Explanation:
- Here, we use a
switch
expression to classify thegrade
. - The keyword
when
is used to apply a condition (in this case, a range of values). - If
grade
is90
or above, it prints"A"
. If it’s between80
and89
, it prints"B"
, and so on.
8. Example with Return Statement in switch
In some cases, you may want to return a value directly from a switch
statement without using break
.
int number = 3;
string result = number switch
{
1 => "One",
2 => "Two",
3 => "Three",
_ => "Unknown number"
};
Console.WriteLine(result);
Explanation:
- In C# 8.0 and later, you can use the expression form of
switch
which allows you to directly return a value from the switch statement without usingbreak
. - Here, if
number
equals1
,2
, or3
, the corresponding string is returned. The underscore (_
) represents the default case (if no match is found).
9. Summary of switch
Statement
- The
switch
statement provides a cleaner way to compare a single expression against multiple values. case
blocks handle specific values, and thedefault
case provides a fallback if no match is found.- Break statements are used to prevent fall-through, although cases can be grouped when needed.
- The
switch
statement is useful for handling both primitive types (likeint
,char
, etc.) and complex types such asstring
andenum
. - Starting from C# 8.0, pattern matching and range checks are supported in
switch
expressions, allowing more advanced scenarios.
This flexibility makes the switch
statement an essential part of decision-making logic in C# programs.