← Back to C# Course | Chapter 15: Modern C# Features | Lesson 2 of 6

Pattern Matching

Pattern matching lets you check what a value looks like and pull out parts of it in one step, like sorting mail by its shape and label. It makes tests short and clear.

In this page:

  1. Pattern Matching
Syntax
csharp
if (obj is type variable)
{
    // use variable
}

string result = value switch
{
    pattern1 => result1,
    pattern2 => result2,
    _ => defaultResult,
};

Pattern Matching

The is operator supports pattern matching, letting you test a value's type or shape and extract it into a variable in one step, like if (obj is string s).

This avoids the older two-step "check the type, then cast" idiom. Pattern matching is widely supported and works well even on older compilers.

Note: if (obj is string s) both checks the type and declares s as that type, usable immediately inside the block.

Example: Pattern Matching

markup
using System;

class Program
{
    static void Describe(object obj)
    {
        if (obj is int i)
            Console.WriteLine($"It's an int: {i}");
        else if (obj is string s)
            Console.WriteLine($"It's a string of length {s.Length}");
        else
            Console.WriteLine("Unknown type");
    }

    static void Main(string[] args)
    {
        Describe(42);
        Describe("hello");
        Describe(3.14);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the discard _ or default case in a switch expression, so an unmatched value throws.
  2. Ordering patterns wrongly, so a general pattern hides a specific one.
  3. Using is with patterns on older C# versions that do not support them.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.