Skip to content

CSharp Basics Switch PatternMatching

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Basics: Pattern Matching with switch

This lesson introduces simple pattern matching with switch expressions and statements in C#.

Related wiki pages:

  • C# overview: CSharpBible.md

Official docs:


1. switch expression

using System;

int value = 5;

string description = value switch
{
    < 0  => "Negative",
    0    => "Zero",
    1    => "One",
    <= 10 => "Between 2 and 10",
    _    => "Greater than 10"
};

Console.WriteLine(description);

2. Type patterns

object input = "hello";

string result = input switch
{
    int i        => $"Integer: {i}",
    string s     => $"String length: {s.Length}",
    null         => "Null value",
    _            => "Unknown type"
};

Console.WriteLine(result);

3. Next steps

  • Explore more advanced patterns (property, positional) in the official docs.
  • Combine pattern matching with exception handling and domain models from other lessons in this wiki.

Clone this wiki locally