Switch expressions are a feature introduced in C# 8.0 that provide a more concise and expressive way to write switch statements. They allow you to assign values directly to a variable based on the result of evaluating different cases, making code more readable and reducing boilerplate.
Here's a basic explanation of switch expressions and an example:
Traditional Switch Statement:
int day = 3;
string dayName;
switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
// ... More cases ...
default:
dayName = "Unknown";
break;
}
Switch Expression:
int day = 3;
string dayName = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
_ => "Unknown"
};
In the switch expression:
day
is the value being evaluated.=>
is used to map each case to its corresponding value._
(underscore) is used as the default case. It's equivalent to thedefault
case in a traditional switch statement.
Switch expressions are concise, readable, and offer pattern-matching capabilities, making them a powerful addition to C#. They are particularly useful when you need to assign values to a variable based on different cases, as demonstrated in the example above.