Click here to Skip to main content
15,881,173 members
Articles / Web Development / ASP.NET
Tip/Trick

Tuples in C# 7.0

Rate me:
Please Sign up or sign in to vote.
4.97/5 (21 votes)
9 May 2017CPOL3 min read 31.9K   132   15   6
C# 7.0 has been introduced with many new useful features. One of them is new datatype "ValueTuple". In this article, I'll be writing about Tuples in C# 7 briefly.

Things We Are Going to Discuss

  • What are Tuples
  • Why we need Tuples
  • Getting Started with a Simple Example
  • Life Without Tuples
  • Demonstration
  • More Readability
  • Adding Names to Tuple Literals
  • Most Simplified Form to Tuples
  • Things to Remember about Tuples

What are Tuples

In general meaning, Tuple is some kind of list which has some order. Items in that list may be different by their type or may be the same.

Why We Need Tuples

Tuples are used to return more than one value from a method.

Note

In order to use this feature of C# 7, if you are working on .NET Framework 4.6.2 or below or on .NET Core, you need to install this package from nuget.

Image 1

After that, you can simply use this type as demonstrated in the following example.

Getting Started with Simple Example

Before going deep into the conceptual and theoretical stories, let’s explore this type directly with a simple example where we have a method which will return The Sum and Count of an Array that we are passing to it.

Here is the method:

C#
private static (int , int) GetCountAndSum(int[] numbers)
       {
           ValueTuple<int, int> VT2; // A Tuple Value

           int sum = numbers.Sum();
           int count = numbers.Count();

           VT2 = (sum, count);

           return VT2;
       }

Now we’ll call the method from main() as below:

C#
static void Main(string[] args)
       {
           int[] numbers = { 22, 22, 33 ,44 ,55 ,55 ,77 };

           ValueTuple<int,int> Sum_Count = GetCountAndSum(numbers);

           Console.WriteLine(" Sum : {0} , Count : {1} ", Sum_Count.Item1 , Sum_Count.Item2);

           Console.ReadLine();
       }

Look at the code. There are a few things you need to understand before working further.

  • Whenever we return more than 1 value using tuples, we access them in the called method using their item number, as we are doing in the above example.
  • ValueTuple is a Generic class in C# which means we have to specify the datatype and their amount using generic classes syntax.
    C#
    ValueTuple<int,int> Sum_Count = ( 0 , 0 );

    Or:

    C#
    ValueTuple<int, int> VT2 = new ValueTuple<int, int>();

More Readability

This is a very simple example of Tuples, but there might be some cases where we would be getting many values rather than just 2 from a method. You might face a problem in such cases. How does the caller know which item number is meant for what? To elaborate the problem, take the above code example for a while and think! How does the caller know which is the sum and which one is the Count?

So to solve this problem, C# is enabling us to give to return types better and more readable names. See the updated method signature in the code below:

C#
private static (int sum, int count) GetCountAndSum(int[] numbers)
       {
           ValueTuple<int, int> VT2;
        // Code Logic here...
           return VT2;
       }

Now you can use these variable names with “dot” operator rather than using “item1” and “item2”, etc.

Image 2

We can use the returning item names rather than using numbers.

Image 3

Here is the updated main() method to receive data in more readable form.

C#
 static void Main(string[] args)
        {
            int[] numbers = { 22, 22, 33 ,44 ,55 ,55 ,77 };

            var Sum_Count = GetCountAndSum(numbers);

Console.WriteLine(" Sum : {0} , Count : {1} ", 
Sum_Count.sum , Sum_Count.count);

            Console.ReadLine();
        }

Adding Names to Tuple Literals

You can also add names to tuple literals to improve readability. See the updated code now.

C#
ValueTuple<int, int> VT2 = (s: 0, c: 0); // A Tuple Literal

Most Simplified Form of Tuples

There is another easy way to consume Tuples in C#, which is..!

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 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.

C#
static void Main(string[] args)
       {
           int[] numbers = { 22, 22, 33 ,44 ,55 ,55 ,77 };

           var (sum, count)= GetCountAndSum(numbers);

           Console.WriteLine(" Sum : {0} , Count : {1} ", sum , count);

           Console.ReadLine();
       }

In the end, remember few things about Tuple Type in C# 7.

Life Without Tuples

Without using this type previously, we use different ways to return more than 1 value from a method which was time consuming and difficult.

  • Out parameters
  • Using arrays
  • System.Typle return types
  • Anonymous types

Things to Remember About Tuples

Till then, we are using the same pair of tuples.

  • Tuple are struct, which mean they are value types:

    Image 4

    They are extending Int class.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer @AmmarTheTrainer
Pakistan Pakistan
I'm a content writer , Community Speaker, Technical Counselor , Blogger , C# Geek and C# Lover. Love to develop apps. Love to work on System Designing , Software Architecture , Database Designing .

Comments and Discussions

 
GeneralMy vote of 5 Pin
Bohdan Stupak18-May-17 1:23
professionalBohdan Stupak18-May-17 1:23 
GeneralRe: My vote of 5 Pin
Ammar Shaukat18-May-17 1:41
professionalAmmar Shaukat18-May-17 1:41 
QuestionVS Version? Pin
FEscobarO12-May-17 6:40
FEscobarO12-May-17 6:40 
AnswerRe: VS Version? Pin
Ammar Shaukat12-May-17 7:01
professionalAmmar Shaukat12-May-17 7:01 
GeneralRe: VS Version? Pin
FEscobarO20-Aug-18 3:27
FEscobarO20-Aug-18 3:27 
GeneralMy vote of 5 Pin
Carsten V2.010-May-17 23:28
Carsten V2.010-May-17 23:28 
Good to know, thanks for posting! Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.