Language: EN

csharp-que-son-tuplas

What are and how to use tuples in C#

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

Unlike classes or structs, tuples are simpler and are designed to simplify the handling of multiple values without the need 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 about Tuples
consult the Introduction to Programming Course read more ⯈ :::

Tuple Syntax

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

var tuple = (value1, value2);

Where,

  • value1, value2, are the values that make up the tuple.

It is possible to create a tuple with any number of values. Although it is also not advisable to create an overly long tuple, as it is not its purpose.

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

Basic Example

Let’s see it easier 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 containing 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. But frankly, I don’t understand why anyone would want to do this 😆.

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

Basic Usage

Accessing tuple elements

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

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 deconstruction

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

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

var (integer, string, 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 to individual variables using deconstruction syntax with assigned names.

Practical Examples

Method that returns a tuple

One of the most common uses of tuples is in methods that need to return multiple values:

// Method that calculates the sum and product of two numbers
public static (int sum, int product) Calculate(int a, int b)
{
    int sum = a + b; // Calculate the sum
    int product = a * b; // Calculate the product
    return (sum, product); // Return a tuple with the results
}

// Usage
var result = Calculate(3, 4); // Call the method and store the result in a tuple
Console.WriteLine($"Sum: {result.sum}, Product: {result.product}"); // Print the results

In this example, the Calculate method returns a tuple containing the sum and product of two integers.

Tuples as method parameters

Tuples can also be used as parameters in methods, allowing multiple values to be passed in a single unit:

// Method that displays information of a person using a tuple as parameter
public static void ShowInformation((string name, int age) person)
{
    Console.WriteLine($"Name: {person.name}, Age: {person.age}"); // Print the name and age
}

// Usage
var person = (name: "John", age: 30); // Create a tuple with the name and age
ShowInformation(person); // Call the method with the tuple as argument

Tuple comparison

Tuples in C# can be directly compared using comparison operators:

// Create tuples to compare
var tuple1 = (1, "Hello");
var tuple2 = (1, "Hello");
var tuple3 = (2, "Goodbye");

// Compare tuples
bool areEqual = tuple1 == tuple2; // true
bool areDifferent = tuple1 != tuple3; // true

// Print comparison results
Console.WriteLine($"tuple1 == tuple2: {areEqual}");
Console.WriteLine($"tuple1 != tuple3: {areDifferent}");

Using tuples in LINQ

Tuples are very useful in LINQ queries, especially when multiple values need to be returned:

// Create a list of tuples representing people
var people = new List<(string name, int age)>
{
    ("John", 25),
    ("Mary", 30),
    ("Peter", 28)
};

// Filter and select people over 25 years old using LINQ
var over25 = people
    .Where(p => p.age > 25)
    .Select(p => (p.name, p.age));

// Print the filtered people
foreach (var person in over25)
{
    Console.WriteLine($"Name: {person.name}, Age: {person.age}");
}

Using tuples as dictionary keys

Another interesting use is to use tuples as multiple keys in a dictionary. This is possible because tuples are immutable.

This is very useful for quickly searching for values based on multiple criteria.

// Create a dictionary with tuples as keys and strings as values
var employees = new Dictionary<(string department, int id), string>();

// Add elements to the dictionary
employees.Add(("Sales", 101), "John Doe");
employees.Add(("Marketing", 102), "Mary Smith");
employees.Add(("IT", 103), "Peter Johnson");

// Search for employees in the dictionary using tuples as keys
var salesEmployee = employees[("Sales", 101)];
var marketingEmployee = employees[("Marketing", 102)];

// Print the search results
Console.WriteLine($"Employee in Sales with ID 101: {salesEmployee}");
Console.WriteLine($"Employee in Marketing with ID 102: {marketingEmployee}");