Deconstruction
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: