Home >Backend Development >C#.Net Tutorial >How to write a new Switch expression in C# 8.0?
The switch expression provides switch-like semantics in the expression context.
switch is a select statement that selects a single switch part from a candidate list to execute based on a pattern match with a matching expression.
If a single expression needs to be tested against three or more conditions, a switch statement is typically used as an alternative to an if-else construct.
New switch writing method
var message = c switch{ Fruits.Red => "The Fruits is red", Fruits.Green => "The Fruits is green", Fruits.Blue => "The Fruits is blue" };
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(); } }
The Fruits is green The Fruits is green
The above is the detailed content of How to write a new Switch expression in C# 8.0?. For more information, please follow other related articles on the PHP Chinese website!