The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. So, with switch statement you always use some repetitive case and break keywords and also use default statement as shown in the below example:
Example:
using System;
public class GFG {
public static void Main(String[] args)
{
int gitem = 8;
switch (gitem) {
case 2:
Console.WriteLine( "Hello" );
break ;
case 4:
Console.WriteLine( "Bonjour" );
break ;
case 6:
Console.WriteLine( "Konnichiwa" );
break ;
case 8:
Console.WriteLine( "Namaste" );
break ;
case 10:
Console.WriteLine( "Anyoung haseyo" );
break ;
default :
Console.WriteLine( "No greeting found" );
break ;
}
}
}
|
Output:
Namaste
This is the basic introduction of the switch statement. Now coming to the main topic, as we know that Microsoft has released the latest version of C# that is C# 8.0. In C# 8.0, the developers made some improvements in the switch statement and after improvements, the switch statement is converted into switch expression and the improvements are as follows:
- The variable used in switch expression is now coming before the switch keyword.
- Colon (:) and case keyword are replaced with arrows (=>). Which makes the code more compact and readable.
- The default case is now replaced with a discard(_).
- And the body of the switch is expression, not a statement.
Now, we modify the above example, according to the new improvements. These new improvements make our program more compact and easy to read as compared to the traditional method.
Example 1:
using System;
public class GFG {
public static void Main(String[] args)
{
var gitem = 4;
var res = gitem switch {
2 => "Hello" ,
4 => "Bonjour" ,
6 => "Namaste" ,
8 => "Anyoung haseyo" ,
_ => "No greeting found" ,
};
Console.WriteLine(res);
}
}
|
Output:
Bonjour
Example 2:
using System;
public class GFG {
public static void Main(String[] args)
{
var sitem = "Second" ;
var res = sitem switch {
"First" => "C#" ,
"Second" => "Java" ,
"Third" => "C++" ,
"Fourth" => "Python" ,
_ => "Not Language found !" ,
};
Console.WriteLine( "Favorite Language: {0} " , res);
}
}
|
Output:
Favorite Language: Java