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.
If you want to learn more about Tuples
check out the Introduction to Programming Course read more
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
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 method Calculate
returns a tuple that contains 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 about a person using a tuple as a 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: "Luis", age: 30); // Create a tuple with the name and age
ShowInformation(person); // Call the method with the tuple as an argument
Tuple Comparison
Tuples in C# can be compared directly 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)>
{
("Luis", 25),
("María", 30),
("Pedro", 28)
};
// Filter and select people older than 25 using LINQ
var olderThan25 = people
.Where(p => p.age > 25)
.Select(p => (p.name, p.age));
// Print the filtered people
foreach (var person in olderThan25)
{
Console.WriteLine($"Name: {person.name}, Age: {person.age}");
}
Using Tuples as Dictionary Keys
Another interesting use is employing tuples as multiple keys in a dictionary. This is possible since tuples are immutable.
This is very useful for quickly looking up 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), "Luis Pérez");
employees.Add(("Marketing", 102), "María López");
employees.Add(("IT", 103), "Pedro González");
// Look up 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}");