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

Deconstruction क्या है

Deconstruction किसी bundle को अलग named variables में unpack करता है, जैसे tray से sandwich और drink उतारना। आप एक ही line में हर टुकड़ा पा लेते हैं।

In this page:

  1. Deconstruction
Syntax
csharp
var (variable1, variable2) = MethodReturningTuple();
(type a, type b) = tuple;

Deconstruction

Deconstruction किसी tuple (या Deconstruct method वाली किसी भी type) को एक statement में सीधे अलग named variables में unpack करता है।

यह result.Item1-style access लिखने से बचने के लिए tuple-returning methods के साथ स्वाभाविक रूप से जोड़ी बनाता है। आप इस syntax को support करने के लिए अपनी classes में भी एक Deconstruct method जोड़ सकते हैं।

Note: किसी deconstruction में जब आपको किसी एक value की ज़रूरत न हो तो placeholder के रूप में _ उपयोग करें।

उदाहरण: Deconstruction

markup
using System;

class Program
{
    static (int Count, double Average) Analyze(int[] numbers)
    {
        int sum = 0;
        foreach (int n in numbers) sum += n;
        return (numbers.Length, (double)sum / numbers.Length);
    }

    static void Main(string[] args)
    {
        (int count, double average) = Analyze(new int[] { 4, 8, 15 });
        Console.WriteLine(count);
        Console.WriteLine(average);
    }
}
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. गलत संख्या में variables में deconstruct करना, जैसे दो-value tuple के लिए var (count, avg, extra) = Analyze(nums);, जो compile नहीं होता।
  2. यह मान लेना कि variables नाम से match होते हैं, जबकि deconstruction position से होता है, इसलिए var (average, count) = ... values को चुपचाप बदल देता है।
  3. discard _ उपयोग करने के बजाय ज़रूरत न होने वाले variables declare करना, जैसे var (count, _) = Analyze(nums);।
🔒

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.