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

Deconstruction

In this page:

  1. Deconstruction

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);
    }
}
🔒

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.