Language: EN

csharp-que-son-tuplas

What are and how to use tuples in C#

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 the handling of 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.

Tuple Syntax

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

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

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

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

Although it is also not advisable to create a very long tuple, as that is not its purpose.

Basic Example

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

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

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

We could also declare the tuple explicitly, specifying the types of the tuple.

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

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

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

But frankly, I don’t understand why anyone would want to do this, given 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

Named Tuples

It is also possible to assign names to the elements of a tuple. This is 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

Tuple Destructuring

We can also use destructuring syntax on tuples 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;

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

Practical Examples