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

Pattern Matching

In this page:

  1. Pattern Matching

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);
    }
}
🔒

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.