Use of Tuple in C#

When writing C# code, we often need to return multiple values from a method. Traditionally, we might create a custom class or struct, or use out parameters. However, since .NET Framework 4.0, we have another option — tuples.

Tuples provide a lightweight way to group multiple values into a single object without creating a new custom type.


What is a Tuple?

A tuple is simply an object that can hold a specific number of elements, each potentially of a different type.
Tuples are defined in the System namespace as generic classes, such as:

Tuple<T1>
Tuple<T1, T2>
Tuple<T1, T2, T3>
...
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>

Each type parameter represents the type of one element in the tuple.


Creating and Using Tuples

Let’s look at a simple example.

using System;

class Program
{
    static void Main()
    {
        var person = Tuple.Create("John", "Doe", 30);

        Console.WriteLine("First Name: " + person.Item1);
        Console.WriteLine("Last Name: " + person.Item2);
        Console.WriteLine("Age: " + person.Item3);
    }
}

Output:

First Name: John
Last Name: Doe
Age: 30

Here, the Tuple.Create() method automatically infers the types for us.
Alternatively, we could create it explicitly:

Tuple<string, string, int> person = new Tuple<string, string, int>("John", "Doe", 30);

Returning Multiple Values from a Method

One of the most common uses for tuples is returning multiple values from a function.

using System;

class Program
{
    static void Main()
    {
        var result = GetMinMax(new int[] { 2, 8, 5, 3 });

        Console.WriteLine("Min: " + result.Item1);
        Console.WriteLine("Max: " + result.Item2);
    }

    static Tuple<int, int> GetMinMax(int[] numbers)
    {
        int min = int.MaxValue;
        int max = int.MinValue;

        foreach (var num in numbers)
        {
            if (num < min) min = num;
            if (num > max) max = num;
        }

        return Tuple.Create(min, max);
    }
}