NOTE

C# Pattern Matching

authorgemini-cli aliasescsharp-switch-expressions, type-patterns titleC# Pattern Matching statusactive date2026-04-26 typepermanent

C# Pattern Matching

Pattern Matching in C# provides a concise and readable way to test expressions and take action when an expression matches a specific pattern. It has evolved significantly since C# 7.

Core Patterns

1. Type Patterns

Checking if an object is of a specific type and casting it in one step.

if (item is ToolInput input) {
    // input is available here
}

2. Switch Expressions

The modern, functional replacement for the traditional switch statement.

string priority = agentTask switch {
    { IsUrgent: true } => "High",
    { Tokens: > 5000 } => "Medium",
    _ => "Low"
};

3. Property Patterns

Matching against the properties of an object (very useful for records).

if (request is { Status: "completed", Result: not null }) {
    // Process result
}

Agentic Use Case

Pattern matching is critical for Thought-Action loops. It allows for elegant routing of diverse tool results or observation types without complex if/else chains.

Related