Tuples With New Features In C# 7.0

Recently, Microsoft announced various new features in C# 7.0 with Visual Studio 2017. In C# 7.0, some new feature of tuples are enhanced with Visual Studio 2017. Tuples aren’t new in C# or.NET. They were first introduced as a part of.NET Framework 4.0. This useful feature of the tuple is all about returning multiple value without having:

  1.  A class and list<> of the class. 
  2. Array, observableCollection, ArrayList or Dictionary.
  3. A series of ref or out parameters.  
It is similar to the code snippet given below.
  1. public (string name, string dept, int id) GetData()  
  2.        {  
  3.            return ("Avnish""R&D", 001);  
  4.        } 
Before C# 7.0, the use of tuple is given below.
  1. public Tuple<string, string, int> GetData2()  
  2.       {  
  3.           return new Tuple<string, string, int>("Rakesh""Marketing", 002);  
  4.       } 
This first thing to be noted is that it is not included automatically in a new project. You must include the System.ValueTuple Nuget package to take an advantage of it in your Visual studio 2017 or its community edition.
 
Let's create a console project for demo.
 
Step 1

Create a new 'Console App' in Visual Studio 2017 RC or Visual Studio 2017.

Create console app

Step 2

Go to
add a NuGet package. By right click to "References" in Solution Explorer, click on "Manage NuGet Package". Now, search for "System.ValueTuple" and install such package.



Step 3

For
use of tuples, add the code given below in Program.cs.

  
  1. namespace TupleDemo  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             Demo demo = new Demo();  
  8.             var result = demo.GetData();  
  9.             Console.WriteLine("Name= " + result.name + " Dept = " + result.dept + " Id= " + result.id);  
  10.             var result2 = demo.GetData2();  
  11.             Console.WriteLine("Name= " + result2.Item1 + " Dept = " + result2.Item2 + " Id= " + result2.Item3);  
  12.             var result3 = demo.GetData3();  
  13.             Console.WriteLine("Name= " + result3.Item1 + " Dept = " + result3.Item2 + " Id= " + result3.Item3);  
  14.             Console.ReadKey();  
  15.         }  
  16.     }  
  17.     class Demo  
  18.     {  
  19.         public (string name, string dept, int id) GetData()  
  20.         {  
  21.             return ("Avnish""R&D", 001);  
  22.         }  
  23.         public Tuple<string, string, int> GetData2()  
  24.         {  
  25.             return new Tuple<string, string, int>("Rakesh""Marketing", 002);  
  26.         }  
  27.         public (string, string, int) GetData3()  
  28.         {  
  29.             return ("Mukesh""Testing", 003);  
  30.         }  
  31.     }  
  32.   
  33. }   
Step 4

Build and run the project.
 


Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all