The switch expression provides for switch-like semantics in an expression context
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.
The switch statement is often used as an alternative to an if-else construct if a single expression is tested against three or more conditions.
Example
New way of Writing the Switch
var message = c switch{
Fruits.Red => "The Fruits is red",
Fruits.Green => "The Fruits is green",
Fruits.Blue => "The Fruits is blue"
};Example 1
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
switch (c){
case Fruits.Red:
Console.WriteLine("The Fruits is red");
break;
case Fruits.Green:
Console.WriteLine("The Fruits is green");
break;
case Fruits.Blue:
Console.WriteLine("The Fruits is blue");
break;
default:
Console.WriteLine("The Fruits is unknown.");
break;
}
var message = c switch{
Fruits.Red => "The Fruits is red",
Fruits.Green => "The Fruits is green",
Fruits.Blue => "The Fruits is blue"
};
System.Console.WriteLine(message);
Console.ReadLine();
}
}Output
The Fruits is green The Fruits is green