csharp-que-son-tuplas

What are and how to use tuples in C#

  • 5 min

In C#, tuples are lightweight data structures that allow grouping multiple values of different types into a single unit.

Unlike classes or structs, tuples are simpler and are designed to simplify handling multiple values (they save us from having to define additional types).

In C#, tuples are immutable. This means that once created, their values cannot be changed.

If you want to learn more, check out the Introduction to Programming Course

Tuple Syntax

Tuples can be declared using the () operator as follows.

var tuple = (value1, value2);
Copied!
  • value1, value2 are the values that make up the tuple.

It’s possible to create a tuple with any number of values. In the previous example I used two, but it could be three, four, or as many as you want.

var tuple = (value1, value2, value3, ...);
Copied!

Although you shouldn’t create an extremely long tuple either, that’s not their purpose.

Basic Example

Let’s see it more easily with an example. This is how we would create a tuple in C#,

var myTuple = (1, "Hello", 3.14);
Copied!

In this case, we have created a tuple containing an int, a string, and a double.

We could also declare the tuple explicitly, specifying the tuple’s types.

(int, string, double) myTuple = (1, "Hello", 3.14);
Copied!

Finally, we can create the tuple using the Tuple<...> class.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "Hello", true);
Copied!

But frankly, I don’t understand why anyone would want to do this, having the previous syntax 😆.

Basic Usage

Accessing Tuple Elements

We can access the elements of a tuple using the properties Item1, Item2, etc.

var tuple = (1, "Hello", true);

Console.WriteLine(tuple.Item1); // 1
Console.WriteLine(tuple.Item2); // Hello
Console.WriteLine(tuple.Item3); // True
Copied!

Named Tuples

It is also possible to assign names to the elements of a tuple. These are known as named tuples. In general, they are more convenient than “unnamed” tuples.

var tuple = (number: 1, text: "Hello", boolean: true);

Console.WriteLine(tuple.number); // 1
Console.WriteLine(tuple.text); // Hello
Console.WriteLine(tuple.boolean); // True
Copied!

Tuple Deconstruction

We can also use tuple deconstruction syntax to break it down into its original values.

var tuple = (1, "Hello", 3.14);

var (integer, stringVal, number) = tuple;

// if you prefer to specify the types
(int number, string text, bool boolean) = tuple;
Copied!

In this case, we are assigning the elements of the tuple tuple to individual variables using deconstruction syntax with assigned names.

Practical Examples