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

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

WBOY
Release: 2023-08-25 18:57:02
forward
1539 people have browsed it

如何在 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"
};
Copy after login

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();
   }
}
Copy after login

Output

The Fruits is green
The Fruits is green
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template