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

Pattern Matching क्या है

Pattern matching आपको एक ही step में यह जांचने और इसके हिस्से निकालने देता है कि कोई value कैसी दिखती है, जैसे mail को उसके shape और label से sort करना। यह tests को छोटा और साफ़ बनाता है।

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

is operator pattern matching support करता है, आपको एक ही step में किसी value का type या shape जांचने और इसे एक variable में निकालने देते हुए, जैसे if (obj is string s)।

यह पुराने दो-step "type जांचो, फिर cast करो" idiom से बचाता है। Pattern matching व्यापक रूप से supported है और पुराने compilers पर भी अच्छी तरह काम करता है।

Note: if (obj is string s) दोनों type जांचता है और s को उस type के रूप में declare करता है, block के अंदर तुरंत उपयोग करने योग्य।

उदाहरण: 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. #}
आम गलतियां
  1. किसी switch expression में discard _ या default case भूल जाना, जिससे एक unmatched value throw करती है।
  2. patterns को गलत order में रखना, जिससे एक general pattern एक specific वाले को छुपा देता है।
  3. पुराने C# versions पर patterns के साथ is उपयोग करना जो उन्हें support नहीं करते।
🔒

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.