Tuple Deconstruction allows you to “unpack” the values of a tuple into individual variables. This makes it easier to work with the values inside the tuple, especially when dealing with tuples returned from methods.
With deconstruction, you can assign the tuple’s elements directly to variables, which makes your code more concise and readable.
Example:
using System;
public class MyProgram
{
public static void Main()
{
// Creating a tuple
var (name, age) = (Name: "John", Age: 30);
// Accessing tuple elements by name
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
Output:
Explanation:
In the above code var (name, age) = (Name: “John”, Age: 30);, the tuple employee is deconstructed, and its elements are assigned to the variables name and age. The order of the variables in the deconstruction matches the order of elements in the tuple.
Deconstruction with Named Tuples
You can also use tuple deconstruction with named tuples to make your code even more readable
Example:
using System;
public class MyProgram
{
public static void Main()
{
// Creating a named tuple
var employee = (Name: "John", Age: 35);
// Deconstructing the tuple into individual variables
var (name, age) = employee;
// Accessing tuple elements by name
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
Output:
Explanation:
In the above code var (name, age) = employee;, the tuple employee is deconstructed, and its elements are assigned to the variables name and age. The order of the variables in the deconstruction matches the order of elements in the tuple.