Pattern matching
Pattern matching was introduced in C# 7, but version 8 of the language specification widens its usage by smoothing the syntax and making it more compact and readable. This chapter will avoid repeating the features already seen in the previous versions and just focus on the new concepts.
The popular switch
statement has evolved in C# to become an expression with a very fluent syntax. For example, suppose you are reading the console keys in an application using the Console.ReadKey
method to get the colors matching the R
, G
, and B
characters:
public Color ToColor(ConsoleKey key) {     return key switch     {         ConsoleKey.R => Color.Red,         ConsoleKey.G => Color.Green,         ConsoleKey.B => Color.Blue,         _ => throw new ArgumentException...