Home  >  Article  >  Backend Development  >  How to write a new Switch expression in C# 8.0?

How to write a new Switch expression in C# 8.0?

WBOY
WBOYforward
2023-08-25 18:57:021442browse

如何在 C# 8.0 中编写新的 Switch 表达式?

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.

Example

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"
};

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete