C# Tuple
A tuple
is a data structure that can hold multiple elements of different types. Tuples are used to group together related pieces of data and are particularly useful when you need to return multiple values from a method or store heterogeneous data in a single variable.
Tuples were introduced in C# 7.0 and provide a convenient way to work with ordered sets of values.
Example of Tuple
in C#.
using System;
class Program
{
static void Main()
{
// Creating a tuple with two elements
var person = Tuple.Create("John", 25);
// Accessing elements of the tuple
Console.WriteLine($"Name: {person.Item1}, Age: {person.Item2}");
// You can also use named elements for better readability (C# 7.0 and later)
var namedPerson = (Name: "Jane", Age: 30);
Console.WriteLine($"Name: {namedPerson.Name}, Age: {namedPerson.Age}");
}
}
Starting from C# 7.0, you can also use the ValueTuple struct, which provides improved performance compared to the Tuple class. ValueTuple allows you to name its elements for better readability.
Here is the example.
using System;
class Program
{
static void Main()
{
// Creating a value tuple with named elements
var person = (Name: "Alice", Age: 22);
// Accessing elements of the value tuple
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
Tuples are particularly handy in scenarios where defining a separate class or struct for a small set of related values might be overkill.
They provide a lightweight way to work with multiple values without the need for defining a custom data structure.