C# Tuple

A Tuple is a lightweight data structure in C# that can hold a fixed-size collection of elements, where each element can have a different type. The tuple allows you to group multiple values into a single object.

Tuples are often used for returning multiple values from a method or when you need to group data without creating a custom class or struct.

There are two way to create a tuple

  1. Using the Tuple class
  2. Using Tuple literals

Creating a Tuple using Tuple class


using System;

public class MyProgram
{
    public static void Main()
    {
        // Creating a tuple with two elements using Tuple.Create
        Tuple empTuple = Tuple.Create(1, "John");

        // Accessing tuple elements using id, Name, etc.
        Console.WriteLine($"ID: {empTuple.Item1}, Name: {empTuple.Item2}");
    }
}

Output:

ID: 1, Name: John

Note:

  1. Tuple<int, string>: This is a tuple that contains an int and a string.
  2. You access the elements in the tuple using Item1, Item2, and so on. The items are zero-indexed but are named Item1, Item2, etc., to indicate their order in the tuple.

Creating a Tuple using tuple literals (C# 7.0 and above)


using System;

public class MyProgram
{
    public static void Main()
    {
        // Creating a tuple using tuple literal (C# 7.0 and above)
        var empTuple = (1, "John");

        // Accessing tuple elements using id, Name, etc.
        Console.WriteLine($"ID: {empTuple.Item1}, Name: {empTuple.Item2}");
    }
}

Output:

ID: 1, Name: John

Explanation:

  1. var tuple = (1, “John”): This creates a tuple with an int and a string without explicitly specifying the types. The compiler will infer the types.
  2. The items are still accessible using Item1, Item2, etc

Named Tuples

Starting with C# 7.0, tuples can be named, which makes the code more readable. Instead of accessing items by Item1, Item2, etc., you can give the elements meaningful names.


using System;

public class MyProgram
{
    public static void Main()
    {
         // Creating a named tuple
        var employee = (Name: "John", Age: 35);

        // Accessing tuple elements by name
        Console.WriteLine($"Name: {employee.Name}, Age: {employee.Age}");
    }
}

Output:

Name: John, Age: 35

Explanation:

  1. (Name: “John”, Age: 35): This is a tuple where the elements are named Name and Age. You can access the elements directly using these names.
  2. This provides better clarity than using Item1, Item2, etc.

Advantages of Tuples

1. Easy Return of Multiple Values: Tuples are useful when you need to return multiple values from a method without creating a custom class or struct.

2. Improved Readability with Named Tuples: Named tuples make your code more understandable.