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

Deconstruction

Deconstruction unpacks a bundle into separate named variables, like taking the sandwich and the drink off the tray. You get each piece in one line.

In this page:

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

Deconstruction

Deconstruction unpacks a tuple (or any type with a Deconstruct method) directly into separate named variables in one statement.

It pairs naturally with tuple-returning methods to avoid writing result.Item1-style access. You can also add a Deconstruct method to your own classes to support this syntax.

Note: Use _ as a placeholder in a deconstruction when you don't need one of the values.

Example: 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. #}
Common Mistakes
  1. Deconstructing into the wrong number of variables, like var (count, avg, extra) = Analyze(nums); for a two-value tuple, which does not compile.
  2. Assuming variables are matched by name, when deconstruction is by position, so var (average, count) = ... swaps the values silently.
  3. Declaring variables you do not need instead of using the discard _, as in 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.