Pattern Matching क्या है
Pattern matching आपको एक ही step में यह जांचने और इसके हिस्से निकालने देता है कि कोई value कैसी दिखती है, जैसे mail को उसके shape और label से sort करना। यह tests को छोटा और साफ़ बनाता है।
In this page:
Syntax
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
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. #}
आम गलतियां
- किसी switch expression में discard
_या default case भूल जाना, जिससे एक unmatched value throw करती है। - patterns को गलत order में रखना, जिससे एक general pattern एक specific वाले को छुपा देता है।
- पुराने C# versions पर patterns के साथ
isउपयोग करना जो उन्हें support नहीं करते।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: