Mohammadbourm
2 min readDec 20, 2023

Switch Expression C# 12

Switch expressions in C# 12 provide a robust alternative to conventional switch statements, enabling developers to create code that is both more concise and expressive.

Unlike traditional switch statements where each case is a statement executing a specific action, switch expressions use expressions for each case, allowing the return of a value. This enables developers to encapsulate more intricate logic within a single line of code.

Let’s take a look at an example. Consider the following traditional switch statement:

string day = "Monday";

string dayType = GetDayType(day);
Console.WriteLine($"The type of day is: {dayType}");

static string GetDayType(string day)
{
switch (day.ToLower())
{
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
return "Weekday";
case "saturday":
case "sunday":
return "Weekend";

default:
return "Unknown";
}
}

The following code sets the value of the dayType variable by evaluating the day variable. By leveraging switch expressions, we can streamline this process into a more compact form:

string day = "Monday";

string dayType = day.ToLower() switch
{
"monday" or "tuesday" or "wednesday" or "thursday" or "friday" => "Weekday",
"saturday" or "sunday" => "Weekend",
_ => "Unknown"
};

Console.WriteLine($"The type of day is: {dayType}");

To sum up, the switch expressions introduced in C# 12 provide a robust and succinct alternative to conventional switch statements. They empower developers to craft more expressive code and can be applied in scenarios where traditional switch statements fall short. The inclusion of pattern matching further enhances the versatility of switch expressions, making them a valuable extension to the C# language.

Mohammadbourm

Experienced Senior Software Engineer adept at navigating the development lifecycle with precision. Adaptable and committed to excellence in every project.