C# pattern matching with is and switch
Short answer
Use patterns in is expressions, switch statements and switch expressions to test types, constants, ranges and property values in one readable check. [S1][S2]
Example
string Size(object o) => o switch {
int n when n < 0 => "negative",
int n and < 10 => "small",
string { Length: 0 } => "empty",
null => "null",
_ => "other"
};
Combine patterns with and, or, not. [S2]
Claims
- id: C1 claim: Patterns work in is, switch statements and switch expressions. source: S1 evidence: "C# uses patterns in is expressions, switch statements, and switch expressions."
- id: C2 claim: Patterns can be on the right side of is. source: S1 evidence: "On the right side of the is operator."
- id: C3 claim: Property patterns match nested fields. source: S2 evidence: "test that an expression's properties or fields match nested patterns"
- id: C4 claim: Logical patterns combine patterns. source: S2 evidence: "test that an expression matches a logical combination of patterns"
Sources
- [S1] Pattern matching overview - C#. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
- [S2] Patterns - Pattern matching using the is and switch expressions. - C# reference. Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns . License: CC BY 4.0 (dotnet/docs). Accessed 2026-11-04.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Microsoft Learn, Pattern matching overview - C#, CC BY 4.0 (dotnet/docs); Microsoft Learn, Patterns - Pattern matching using the is and switch expressions. - C# reference, CC BY 4.0 (dotnet/docs).
Cite this
iinventedlight. 2026. "C# pattern matching with is and switch." iinventedlight Library, iil:note:2j2j1dxe, version of 2026-11-04. https://iinventedlight.com/library/notes/csharp-pattern-matching/. License: CC-BY-4.0.
@misc{iil_note_2j2j1dxe,
author = {{iinventedlight}},
title = {{C\# pattern matching with is and switch}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-04},
url = {https://iinventedlight.com/library/notes/csharp-pattern-matching/},
note = {Permanent ID iil:note:2j2j1dxe. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.
For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/csharp-pattern-matching.md.