C# 7.0 New Feature - Tuples In C# 7

In this blog, we are going to learn what Tuples are, why we need Tuples, and what would our life be without Tuples.

To demonstrate the features, I have chosen a simple example of tuple which will return two values - int count, double sum - that will be calculated based on the parameter passed by the type of Ienumerable<int> values.

Things we are going to discuss

What are Tuples

Tuples are used to bundle the related values together without having to create a specific type to hold them.

Life without Tuples

Previously, we used different ways to return more than 1 value from a method which was time-consuming and difficult. Some of them are listed below -
  • Out parameters
  • Using arrays
  • System.Tupels
  • Anonymous types
Why we need Tuples
Tuples are used to return more than one values from a method. 

Getting started with a simple example

In .NET 4.0, a set of Tuple classes was introduced in the framework, which can be used as below.

  1. namespace CSharp7._0_Example  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             IEnumerable<double> values = new double[] { 10, 20, 30, 40, 50, 60 };   
  9.             var t = CountAndSum(values);  
  10.             Console.WriteLine($"There are {t.Item1} values and their sum is {t.Item2}");  
  12.             Console.ReadLine();  
  13.         }  
  15.         private static Tuple<intdouble> CountAndSum(IEnumerable<double> values)  
  16.         {  
  17.             int count = 0;  
  18.             double sum = 0.0;  
  19.             foreach (var value in values)  
  20.             {  
  21.                 count++;  
  22.                 sum += value;  
  23.             }  
  24.             return Tuple.Create(count, sum);  
  25.         }        
  27.     }  
  28. }  

There are two things to notice in C# 4

  1. In C# 4, Tuples were a reference type. This means they must be allocated on the heap, and garbage collected when they’re no longer used. For applications where performance is critical, it can be an issue. Also, the fact that they can be null is often not desirable.

  2. The elements in the tuple don’t have names, or rather, they always have the same names (Item1, Item2, etc), which are not meaningful at all. The Tuple <T1, T2> type conveys no information about what the tuple actually represents. So it is difficult to choose for a larger number of return types.
In C# 7, a new feature is introduced to improve the support for tuples
Add NuGet Package reference from "Add" reference.

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             IEnumerable<double> values = new double[] { 10, 20, 30, 40, 50, 60 };   
  7.             var t = CountAndSum(values);  
  8.             Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");  
  10.             Console.ReadLine();  
  11.         }  
  13.         private static (int count , double sum) CountAndSum(IEnumerable<double> values)  
  14.         {  
  15.             int count = 0;  
  16.             double sum = 0.0;  
  17.             foreach (var value in values)  
  18.             {  
  19.                 count++;  
  20.                 sum += value;  
  21.             }  
  22.             return (count, sum);  
  23.         }      
  25.     }  
More Readability 
You must have observed in the above example that you can create tuples giving only data type and while returning, we need to write Create.Tuple<int,double> and while accessing member, you have to use Item1, Item2, Item3 so one. There was no naming for member name before C# 7.0.

In C# 7.0, you can try this feature right now in Visual Studio 15. However, the ValueTuple<T1, T2> type is not (yet) part of the .NET Framework; to get this example to work, you’ll need to reference the System.ValueTuple NuGet package.

Here, three things are significant to notice.
  1. You can write your return type, in both datatype names (int count , double sum)
  2. You can simply return you variable using return keyword; so, no need to use tuple.create<> method return (count, sum);
  3. Finally, while accessing the method, you can use your name because item1, item2 etc. are not required.

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

Adding Names to Tuple Literals

There is another easy way to consume Tuples in C#. Here, the below example gives an idea of how can you consume Tuples. Rather than obtaining a full blown Tuple type in main() method, we can immediately split the tuple into its parts using some separate variables.

Further, we also don’t need to use the syntax (dot operator for sub items) of Tuple to display its subitems. Instead, you can directly use variable names. See the code in the main() method.

  1. static void Main(string[] args)  
  2.        {  
  3.            int[] numbers = { 10, 20, 30 ,40 ,50 ,60 ,70 };  
  5.            var (sum, count)= GetCountAndSum(numbers);  
  7.            Console.WriteLine(" Sum : {0} , Count : {1} ", sum , count);  
  9.            Console.ReadLine();  
  10.        }  

Hope this blog will help you to understand what improvements are done for tuples in C# 7.0.

If you have any query, please feel free to ask by giving a comment below.