C# – How to deconstruct tuples

Deconstructing a tuple means assigning its fields to several variables at once by using the deconstruction assignment syntax. This is also referred to as destructuring or tuple unpacking. Here’s an example of deconstructing a tuple into two variables:

//create a ValueTuple<string, int> using syntax sugar
var movie = ("The Matrix", 1999);

//deconstruction assignment
var (title, year) = movie;

//Use the variables
Console.WriteLine($"{title} was released in {year}");
Code language: C# (cs)

This outputs:

The Matrix was released in 1999Code language: plaintext (plaintext)

Deconstructing the tuple assigns the fields (Item1 and Item2) to variables based on position. The deconstruction assignment is really doing the following:

  • string title = movie.Item1;
  • int year = movie.Item2;

The variable types are inferred from the tuple field types. You have the option of explicitly declaring the variable types – like this (string title, int year) = movie – but it’s not necessary.

Ignore a tuple field during deconstruction

When you deconstruct a tuple, you can ignore one or more fields by using the discard symbol (_). Tuple deconstruction is based on position. So use the discard symbol in the position of the field(s) you want to ignore. For example, let’s say have a tuple with three fields and you want to ignore the second field. Here’s how you’d do that:

var (title, _, year) = GetMovie();

Console.WriteLine($"{title} was released in {year}");
Code language: C# (cs)

This outputs the following:

Jurassic Park was released in 1993Code language: plaintext (plaintext)

This results in it assigning tuple fields Item1 and Item3 to the variables while ignoring Item2.

Deconstruct tuple to existing variables

You can also deconstruct tuples to existing variables or properties. Here’s an example of populating an object’s properties with the tuple:

var movie = new Movie();
(movie.Title, movie.Year) = ("The Matrix", 1999);
Code language: C# (cs)

This is useful when you want to reduce assignment to a one-liner.

You can also use this approach for swapping variables without needing a temporary variable, like this:

int a = 1;
int b = 2;

(a, b) = (b, a);

Console.WriteLine($"a={a} b={b}");
Code language: C# (cs)

This outputs the swapped variables:

a=2 b=1Code language: plaintext (plaintext)

Leave a Comment