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:
Syntax
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
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);
}
}
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. #}
Common Mistakes
- Deconstructing into the wrong number of variables, like
var (count, avg, extra) = Analyze(nums);for a two-value tuple, which does not compile. - Assuming variables are matched by name, when deconstruction is by position, so
var (average, count) = ...swaps the values silently. - Declaring variables you do not need instead of using the discard
_, as invar (count, _) = Analyze(nums);.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: