Click here to Skip to main content
13,249,087 members (38,902 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.3K views
92 downloads
14 bookmarked
Posted 9 May 2017

Tuples in C# 7.0

, 9 May 2017
Rate this:
Please Sign up or sign in to vote.
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.

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:

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:

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.
    ValueTuple<int,int> Sum_Count = ( 0 , 0 );

    Or:

    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:

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.

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

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

 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.

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.

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:

    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)

Share

About the Author

Ammar Shaukat
Instructor / Trainer Aptech
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 .

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Bohdan Stupak18-May-17 2:23
professionalBohdan Stupak18-May-17 2:23 
GeneralRe: My vote of 5 Pin
Ammar Shaukat18-May-17 2:41
memberAmmar Shaukat18-May-17 2:41 
QuestionVS Version? Pin
FEscobarO12-May-17 7:40
memberFEscobarO12-May-17 7:40 
AnswerRe: VS Version? Pin
Ammar Shaukat12-May-17 8:01
memberAmmar Shaukat12-May-17 8:01 
GeneralMy vote of 5 Pin
Carsten V2.011-May-17 0:28
memberCarsten V2.011-May-17 0:28 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 10 May 2017
Article Copyright 2017 by Ammar Shaukat
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid