Pattern Matching
In this page:
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: