Open to work
Published on

Tuple in C# with usage examples

Authors

image

Tuples were introduced in C# 7.0, and they provide a number of benefits over other data structures, such as:

  • They are more efficient than anonymous types because they are compiled into the same underlying data structure.
  • They are more flexible than arrays because they can contain elements of different data types.
  • They are more concise than creating a new class to store the data.

Tuples can be used in a variety of ways, such as:

  • To return multiple values from a method.
  • To store data that is grouped together logically.
  • To pass data to a method or function.
  • To store data in a collection, such as a list or dictionary.

Tuples in C# 10: Examples

Create a tuple with elements


var person = ("John Doe", 30);

// Access Elements
string name = person.Name;
int age = person.Age;


var product = (12345, "Product Name", 10.50);
(int id, string name, double price) = product;

Console.WriteLine($"Product ID: {id}");
Console.WriteLine($"Product Name: {name}");
Console.WriteLine($"Product Price: {price}");

//Output; 
// Product ID: 12345
// Product Name: Product Name
// Product Price: 10.5

C# 10 also introduces a new feature called "tuple assignment". This feature allows you to assign the elements of a tuple to multiple variables in a single statement. For example, the following code is equivalent to the previous example:

var person = ("John Doe", 30);
(string name, int age) = person;

Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");

Another new feature in C# 10 is the ability to add tuple support to your custom types. To do this, you simply need to implement a public Deconstruct() method that takes out parameters for each element of the tuple.

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public void Deconstruct(out int x, out int y)
    {
        x = X;
        y = Y;
    }
}

Once you have added tuple support to your custom type, you can use it in tuples just like any other type.

var point = new Point(10, 20);
var tuple = (point, 30);
(Point point, int value) = tuple;

Console.WriteLine($"Point: {point}");
Console.WriteLine($"Integer: {value}");

// Output
// Point: (10, 20)
// Integer: 30

Tuple support for custom types can be a useful way to simplify your code and make it more readable.

Examples:

1. Returning Multiple Values from a Method:

Tuples are great for returning multiple values from a method, improving code readability.

public (double area, double perimeter) CalculateRectangleStats(double length, double width)
{
    double area = length * width;
    double perimeter = 2 * (length + width);
    return (area, perimeter);
}

var stats = CalculateRectangleStats(5.0, 3.0);
Console.WriteLine($"Area: {stats.area}, Perimeter: {stats.perimeter}"); 

2. Tuple with Nested Tuples:

Tuples can be nested to represent more complex data structures:

var student = ("John", ("Math", 95), ("Science", 88));
string name = student.Item1;
int mathScore = student.Item2.Item2;
int scienceScore = student.Item3.Item2; 

3. Tuple with Named Elements:

Named elements make tuple usage more expressive:

var point = (X: 10, Y: 20);
Console.WriteLine($"X: {point.X}, Y: {point.Y}"); 

4. Tuple Deconstruction in a Loop:

Tuples can simplify iteration over collections:

var data = new List<(string name, int age)> { ("Alice", 25), ("Bob", 30), ("Charlie", 22) };
foreach (var (name, age) in data)
{
    Console.WriteLine($"Name: {name}, Age: {age}");
}

5. Tuple in a Dictionary:

Tuples can be used as keys in dictionaries:

var studentGrades = new Dictionary<(string firstName, string lastName), int>
{
    { ("John", "Doe"), 95 },
    { ("Alice", "Smith"), 88 },
};

int johnsGrade = studentGrades[("John", "Doe")]; 

6. Tuple Patterns in Switch Statements:

Tuples can be used in pattern matching within switch statements:

var person = ("Alice", 30);

switch (person)
{
    case var (_, age) when age < 18:
        Console.WriteLine("Person is a minor.");
        break;
    case var (name, age) when age >= 18:
        Console.WriteLine($"Welcome, {name}!");
        break;
}

7. Tuple Support in LINQ Queries:

Tuples can be used effectively in LINQ queries:

var scores = new List<(string name, int score)> { ("Alice", 95), ("Bob", 88), ("Charlie", 92) };
var highScorers = scores.Where(s => s.score >= 90).Select(s => s.name);