C# Feature – Switch expressions
Overview
Section titled “Overview”Switch expressions are concise and composable, leveraging pattern matching and exhaustiveness.
Introduced In
Section titled “Introduced In”C# 8 (2019)
Before
Section titled “Before”string ColorName(ConsoleColor c){ switch (c) { case ConsoleColor.Red: return "Red"; case ConsoleColor.Green: return "Green"; default: return "Other"; }}
string ColorName(ConsoleColor c) => c switch{ ConsoleColor.Red => "Red", ConsoleColor.Green => "Green", _ => "Other"};
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Use
_
discard for default; consider completeness with enums.