Packing and Unpacking with C# Tuples

Group elements of different types in a lightweight data structure

Introduction

Available since C# 7.0, a tuple is an ordered sequence of elements used to store multiple items in a single variable without the need to create custom classes or structs.

He’s a tuple I’ve created called product, which combines a Book object with a price, declared with round brackets:

(Book book, decimal price) product = (new Book(
"Best Practices for Software Engineers", "George Marklow"),
8.99m);
Console.WriteLine(product.book.Title);
// Best Practices for Software Engineers
Console.WriteLine(product.book.Author);
// George Marklow
Console.WriteLine(product.price);
// 8.99

As you can see, a tuple allows us to store elements of different types, unlike a C# array where all elements need to be of the same type.

Tuples are also helpful for returning multiple values from a method without using the C# out modifier.

Constructing Tuples

In this tutorial, create a new console application project called TupleDemo and add a Book class:

In this Book class, assign two properties Title and Author, as well as an override of ToString to return a string that represents a Book object:

In the Main method, create a product tuple, which combines a Book object with a price without the need to define a Product class:

In the above example, notice that the first and second elements of the tuple are simply referred to as Item1 and Item2.

For increased readability and convenience, explicitly define the tuple field names as follows:

Otherwise, use var on the left-hand side of the expression and specify the names of the tuple elements on the right-hand-side:

Ignore any elements not intended for use with an underscore. In this example, use an underscore instead of the book variable, but continue to extract and use the price element:

Deconstructing Tuples

We can also go in the opposite direction, deconstructing a tuple into its constituent parts.

In this trivial example, deconstruct a book tuple to extract Title and Author variables:

Visual Studio’s IntelliSense will complain that the Book type is missing a Deconstruct method:

Add the following in the Book class to resolve this:

Return Multiple Values from a Method

We can also define a method that returns a tuple.

In this example, return the total cost for several copies of a book and calculate the delivery charge using an arbitrary calculation. Then, return these two values in a tuple:

I hope that this has been useful for everybody — let me know what you think in the comments section below.

George is a software engineer, author, blogger, and tech enthusiast who believes in helping others to make us happier and healthier.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store