C# Switch Statement
Introduction to Switch
The switch statement in C# is used to execute one block of code from multiple possible options based on the value of an expression.
It is a cleaner alternative to multiple if-else conditions when you are checking a single variable against different constant values.
Syntax of Switch
The switch statement evaluates an expression and matches it with case labels.
Each case should end with a 'break' (or return, throw, or goto) to prevent fall-through unless explicitly intended.
using System;
namespace SwitchExample
{
class Program
{
static void Main(string[] args)
{
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;
}
}
}
}
Wednesday
Switch with Strings
In addition to numbers, C# switch statements support string values.
This makes it useful for handling text-based options in a structured way.
using System;
namespace SwitchString
{
class Program
{
static void Main(string[] args)
{
string color = "red";
switch (color)
{
case "red":
Console.WriteLine("Color is Red");
break;
case "blue":
Console.WriteLine("Color is Blue");
break;
default:
Console.WriteLine("Unknown color");
break;
}
}
}
}
Color is Red
Modern Switch Expressions (C# 8.0+)
C# 8.0 introduced switch expressions, which provide a more concise syntax.
They allow returning values directly instead of writing full case blocks.
using System;
namespace SwitchExpressionExample
{
class Program
{
static void Main(string[] args)
{
int day = 3;
string result = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
_ => "Weekend"
};
Console.WriteLine(result);
}
}
}
Wednesday