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:
Syntax
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
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
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
- Forgetting the discard
_or default case in a switch expression, so an unmatched value throws. - Ordering patterns wrongly, so a general pattern hides a specific one.
- Using
iswith 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: