The switch statement is a cleaner way to compare a single value against
multiple possible matches. Instead of writing a long chain of else if statements,
you can use switch to make your code more readable.
Basic switch Syntax
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;
}
The switch expression is evaluated once. Then C# compares it against each
case value. When it finds a match, it runs the code under that case. The
break statement is important โ it tells C# to exit the switch block.
The default case is like the else in an if-else chain. It runs if none
of the cases match.
switch with Strings
You can also switch on strings:
string fruit = "mango";
switch (fruit.ToLower())
{
case "apple":
Console.WriteLine("Red and crispy.");
break;
case "banana":
Console.WriteLine("Yellow and soft.");
break;
case "mango":
Console.WriteLine("Sweet and tropical.");
break;
default:
Console.WriteLine("Unknown fruit.");
break;
}
Notice I used ToLower() to make the comparison case-insensitive. This way,
whether the user types "Mango", "MANGO", or "mango", it still matches.
Switch Expressions (Modern C#)
Starting with C# 8.0, there is a shorter syntax called switch expressions. They are especially useful when you want to assign a value based on a match:
int score = 85;
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
Console.WriteLine($"Grade: {grade}"); // Grade: B
See how much cleaner that is? The _ is the default case (like default in
the traditional syntax). Switch expressions are great when you are mapping one value
to another.
When to Use switch vs if-else
Use switch when you are comparing one variable against many fixed values.
Use if-else when your conditions are more complex or involve different variables.
There is no right or wrong โ it is about readability.