Tuples in C#

Tuples in C# 7 with Examples

In this article, I am going to discuss the Tuples in C# with examples. Please read our previous article before proceeding to this article where we discussed the Digit Separators in C# with some examples. It is a common thing in the programming world to return more than one value from a method/function. Before using Tuples in C# to return more than one value from a method, let us first understand what are the mechanisms available in C# to return more than one value from a method.

We can return more than one value from a method by using a custom data type (i.e. class) as the return type of the method. But sometimes we don’t need or don’t want to use classes and objects because that’s just too much for the given purpose.

We can also return more than one value from the method by using the “out” parameters. Using “out” parameters quite difficult to understand and moreover, the “out” parameters will not work with the async methods.

Another method to return more than one value from a method to use the dynamic keyword which is introduced in C# 4. But from a performance point of view, we probably don’t want to use dynamic. 

In the .NET framework 4.0, a set of Tuple classes has been introduced. The System.Tuple class provides a type to represent a key-value like property bag which is used to bundle related values together without having to create a specific type to hold them.

Let’s understand Tuples in C# with one example.
class Program
{
    static void Main()
    {
        var values = new List<double>() { 10, 20, 30, 40, 50 };

        var t = Calulate(values);
        Console.WriteLine($"There are {t.Item1} values and their sum is {t.Item2}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static Tuple<int, double> Calulate(IEnumerable<double> values)
    {
        int count = 0;
        double sum = 0.0;
        foreach (var value in values)
        {
            count++;
            sum += value;
        }
        return Tuple.Create(count, sum);
    }
}

When we run the application, it will give us the following output as expected.

Tuples in C#

Problems with the above code:

There are 3 major problems in the above code with Tuple:

The first problem is that the Tuples in C# are classes, i.e. reference types. As reference types, the memory is allocated on the heap area and garbage collected only when they are no longer used. For applications where performance is the major concerns, it can be an issue.

The second problem is that the elements in the tuple don’t have any names or rather they always have the same names (Item1, Item2, etc.) which are not meaningful at all. The Tuple<T1, T2> type does not provide any information about what the tuple actually represents which makes it a poor choice in public APIs.

The third problem is that you can use a maximum of 8 properties in a Tuple in C#. If you want to return more than 8 values from a method,  then again the last argument of the Tuple must be another Tuple. This makes the syntax more difficult to understand.

To overcome the above three problems, C# 7 comes with a new feature which is used to improve the support for tuples in C#. With C# 7, now we are able to declare the tuple types as “inline”, which is like an anonymous type, except that they are not limited to the current method. The Tuples in C# 7 can now have multiple parameters.

Let’s modify the code as shown below to Tuples in C# 7.
class Program
{
    static void Main()
    {
        var values = new List<double>() { 10, 20, 30, 40, 50 };

        var t = Calulate(values);
        Console.WriteLine($"There are {t.Item1} values and their sum is {t.Item2}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (int, double) Calulate(IEnumerable<double> values)
    {
        int count = 0;
        double sum = 0.0;
        foreach (var value in values)
        {
            count++;
            sum += value;
        }
        return (count, sum);
    }
}

When we run the application, it gives us the following output.

Tuples in C#

As you can see in the above code, we are returning two values i.e. int and double from the Calculate method and then we are accessing the values. This is much better. If you want then you can also give specific names to the tuples returning values.

Tuples in C# with named Parameters:

With  C# 7, now we can also have tuples with named parameters. To understand this let’s modify the code as shown below. Here we are providing names for the tuple parameters.

class Program
{
    static void Main()
    {
        var values = new List<double>() { 10, 20, 30, 40, 50 };

        var t = Calulate(values);
        Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static (int count, double sum) Calulate(IEnumerable<double> values)
    {
        int count = 0;
        double sum = 0.0;
        foreach (var value in values)
        {
            count++;
            sum += value;
        }
        return (count, sum);
    }
}

When we run the application, it will give us the following output:Tuples in C#

The point that you need to keep focus is that when you use Tuples with named parameters then you will get IntelliSense support for these names as well and you can also use them in our code.

Guidelines to use Tuples:

Basically, one and the most important question that comes to our mind is when to use Tuples and when to use Classes to return more than one values from a method in C#.

The answer is it depends on the business requirement. However, there are some guidelines and rules that you need to follow which will guide you to choose between them:

The Tuples in C# 7 are values, so they are copied by value, rather than by reference.

Most of the time, this should not be an issue. However, if you are passing around tuples of large structs, this might have an impact on the performance of the application. Ref locals/returns can be used to work around these performance issues that we will discuss in our upcoming articles. As the tuples in C# 7 are values, so modifying a copy will not change the original copy. 

Tuples are lightweight

Tuples are much simpler to write than types as they are less verbose and the declaration can be “inline” (i.e. declared at the point of use). This works well when declaring a method that returns multiple values, for example.

However, because they are declared at the point of use, if you have MethodA that calls MethodB that calls MethodC and each returns a tuple you’ll need to redefine the tuple at every stage. There isn’t (yet) a way of creating an alias of a tuple and re-using it across multiple methods.

Just use common sense

For any situation where you might consider using a tuple: simply ask yourself the question: “will a tuple simplify the code here“. If the answer is “yes“, then use one. And that ultimately is the primary consideration over whether to use a tuple or a custom class.

So in the simple word we can say that Tuple is an ordered sequence of heterogeneous objects. The Tuples in C# are going to be used when a method is going to return more than one values.

In the next article, I will discuss Deconstruction in C# some examples.

SUMMARY

In this article, I try to explain the Tuples in C# 7 step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *