Dec 15, 2019 05:48 PM
(This post was last modified: Dec 15, 2019 08:10 PM by MavenGradle.)
Introduction:
This is going to be a short but informative tutorial regarding a new feature that was introduced in C# 8.0 called a switch expression. If you've been keeping up to date about C#, you should already know about this. Chances are, you'll be using it already. This tutorial is mostly meant for those among us who have no clue what this is all about or how switch expressions work in the latest C# language specifications.
Requirements:
Switch statements:
Let's start of by explaining what a switch statement is. I'm going to be brief about this, since this is one of the most basic features that C# has to offer. If you do not know what switch statements are and how they operate, I would recommend that you take a look at the requirements above. There's a link there that contains a lot of information that you can use to learn and enhance your programming skills. Regardless, Microsoft has perfectly laid this information out for us in a single scentence:
https://docs.microsoft.com/en-us/dotnet/...rds/switch
An example of a switch statement:
Now in this particular example, the output of the console will be "Case 1", seeing how the variable that is being evaluated (caseSwitch) is equal to one and matches the first case. The default case is the one that will be reached when all other cases do not match the evaluation.
These kind of switch statements can greatly improve general code readability and maintainability when compared to if statements. Especially if your if statements are extremely large. In some cases switch statements can perform better than if statements as well, but the opposite can be true as well, so take this with a grain of salt and always select the best method of action.
If we go back to our code and convert the example above which contains a switch statement to an if statement, it would look something like this:
As you can see, it becomes harder and harder to maintain as more options are added to the list of cases that can be handled.
Switch expressions:
Now imagine you're using a switch statement to evaluate an input and to return some kind of value, depending on the case, in a method:
With the new switch expressions, the example above can be simplified to the following:
The default case has been replaced with the "_" character, simplifying and reducing the amount of text you have to type. In addition to that, arrow functions are used to remove the braces of the function and to indicate a return value, this once again reduces the amount of text you, as a programmer, have to type and increases readability. All of this effectively turn the body to an expression and as such, it can no longer be considered a statement.
The variable that is being evaluated is also placed before the switch keyword. It has been implemented this way to make it easier to distinguish switch expressions and switch statements.
Switch expressions can also be used to assign (or yield) a value to a variable depending on the case, like so:
Some thoughts:
All in all, these changes are made to increase the readability and maintainability of your code. It is also useful to know that C# 8.0 features are available in Visual Studio 2019 and of course in the wonderful JetBrains Rider. These features have to be explicitly turned on before you can use them or you will face errors and warnings. Do note that you should also be using the latest version of your IDE, because these features, for example, will not work in Visual Studio 2010.
In order to enable C# 8.0 you will need to edit your .csproj file and use the following attribute for your configurations:
I hope you learned something.
This is going to be a short but informative tutorial regarding a new feature that was introduced in C# 8.0 called a switch expression. If you've been keeping up to date about C#, you should already know about this. Chances are, you'll be using it already. This tutorial is mostly meant for those among us who have no clue what this is all about or how switch expressions work in the latest C# language specifications.
Requirements:
- Visual Studio 2019 / Jetbrains Rider (latest versions)
- Knowledge about switch statements
- Basic understanding of C# programming
Switch statements:
Let's start of by explaining what a switch statement is. I'm going to be brief about this, since this is one of the most basic features that C# has to offer. If you do not know what switch statements are and how they operate, I would recommend that you take a look at the requirements above. There's a link there that contains a lot of information that you can use to learn and enhance your programming skills. Regardless, Microsoft has perfectly laid this information out for us in a single scentence:
Quote:The switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.
https://docs.microsoft.com/en-us/dotnet/...rds/switch
An example of a switch statement:
Code
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
case 4:
Console.WriteLine("Case 4");
break;
default:
Console.WriteLine("Default case");
break;
}Now in this particular example, the output of the console will be "Case 1", seeing how the variable that is being evaluated (caseSwitch) is equal to one and matches the first case. The default case is the one that will be reached when all other cases do not match the evaluation.
These kind of switch statements can greatly improve general code readability and maintainability when compared to if statements. Especially if your if statements are extremely large. In some cases switch statements can perform better than if statements as well, but the opposite can be true as well, so take this with a grain of salt and always select the best method of action.
If we go back to our code and convert the example above which contains a switch statement to an if statement, it would look something like this:
Code
int caseSwitch = 1;
if (caseSwitch == 1) {
Console.WriteLine("Case 1");
} else if (caseSwitch == 2) {
Console.WriteLine("Case 2");
} else if (caseSwitch == 3) {
Console.WriteLine("Case 3");
} else if (caseSwitch == 4) {
Console.WriteLine("Case 4");
} else {
Console.WriteLine("Default case");
}As you can see, it becomes harder and harder to maintain as more options are added to the list of cases that can be handled.
Switch expressions:
Now imagine you're using a switch statement to evaluate an input and to return some kind of value, depending on the case, in a method:
Code
private string GetResult(int input) {
switch (input)
{
case 1:
return "a";
case 2:
return "b";
case 3:
return "c";
case 4:
return "d";
case 5:
return "e";
case 6:
return "f";
case 7:
return "g";
default:
throw new ArgumentOutOfRangeException(nameof(input));
}
}With the new switch expressions, the example above can be simplified to the following:
Code
private string GetResult(int input) =>
input switch
{
1 => "a",
2 => "b",
3 => "c",
4 => "d",
5 => "e",
6 => "f",
7 => "g",
_ => throw new ArgumentOutOfRangeException(nameof(input)),
};The default case has been replaced with the "_" character, simplifying and reducing the amount of text you have to type. In addition to that, arrow functions are used to remove the braces of the function and to indicate a return value, this once again reduces the amount of text you, as a programmer, have to type and increases readability. All of this effectively turn the body to an expression and as such, it can no longer be considered a statement.
The variable that is being evaluated is also placed before the switch keyword. It has been implemented this way to make it easier to distinguish switch expressions and switch statements.
Switch expressions can also be used to assign (or yield) a value to a variable depending on the case, like so:
Code
var result = input switch
{
1 => true,
2 => true,
_ => false
};Some thoughts:
All in all, these changes are made to increase the readability and maintainability of your code. It is also useful to know that C# 8.0 features are available in Visual Studio 2019 and of course in the wonderful JetBrains Rider. These features have to be explicitly turned on before you can use them or you will face errors and warnings. Do note that you should also be using the latest version of your IDE, because these features, for example, will not work in Visual Studio 2010.
In order to enable C# 8.0 you will need to edit your .csproj file and use the following attribute for your configurations:
Code
<LangVersion>8.0</LangVersion>I hope you learned something.
![[Image: vp6iypF.gif]](https://i.imgur.com/vp6iypF.gif)





![[Image: narwinsig.gif]](https://image.ibb.co/jf6HBa/narwinsig.gif)
