← All notes

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

Sources

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

Permanent ID: iil:note:2j2j1dxe

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.},
}

Markdown

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.