How to deconstruct tuples in C#

By FoxLearn 3/5/2025 3:46:04 AM   27
Deconstructing a tuple allows you to assign its values to multiple variables simultaneously using the deconstruction assignment syntax.

This is also known as tuple unpacking or destructuring.

Here's an example of deconstructing a tuple with three elements:

// Create a ValueTuple<int, string, double> using tuple literal
var product = (123, "Laptop", 899.99);

// Deconstruction assignment
var (id, name, price) = product;

// Use the variables
Console.WriteLine($"Product {id}: {name} costs ${price}");

Output:

Product 123: Laptop costs $899.99

In this case, deconstructing the tuple assigns the fields (Item1, Item2, and Item3) to the variables based on their positions. The deconstruction assignment can be thought of as:

int id = product.Item1;
string name = product.Item2;
double price = product.Item3;

Ignore a Tuple Field During Deconstruction

You can ignore one or more tuple fields by using the discard symbol (_). Since tuple deconstruction is position-based, place the discard symbol in the position of the field(s) you want to ignore. For instance, let’s say you have a tuple with four elements and you only care about the first and the last:

var (id, _, _, price) = GetProduct();

// Use the variables
Console.WriteLine($"Product {id} costs ${price}");

Output:

Product 456 costs $199.99

In this example, Item2 and Item3 are ignored, while Item1 and Item4 are assigned to id and price.

Deconstruct Tuple into Existing Variables

You can deconstruct tuples directly into existing variables or properties of an object.

For example, let’s populate an object’s properties with tuple values:

var product = new Product();
(product.ProductId, product.ProductName) = (789, "Smartphone");

Console.WriteLine($"Product {product.ProductId}: {product.ProductName}");

This is convenient when you want to simplify assignments to a single line.

Swap Variables Using Tuple Deconstruction

Tuple deconstruction can also be used to swap variables without the need for a temporary one:

int x = 10;
int y = 20;

// Swap values
(x, y) = (y, x);

Console.WriteLine($"x={x} y={y}");

Output:

x=20 y=10

By using tuple deconstruction, the values of x and y are swapped in a concise and elegant manner.