C# Feature - Constant patterns
Overview
Section titled “Overview”Constant patterns let you match against literal values or named constants with the is operator or inside switch expressions.
Introduced In
Section titled “Introduced In”C# 7.0 (2017)
Before
Section titled “Before”if (status == "Ready"){ Start();}if (status is "Ready"){ Start();}Annotated Example
Section titled “Annotated Example”string message = responseCode switch{ 200 => "OK", 404 => "Missing", _ => "Other"};Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Prefer constant patterns inside broader pattern matching code to keep style consistent.
- Use the discard pattern
_for the fallback branch.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- C# 7 introduced constant and type patterns.