In Focus

C# ValueTuple Code Example

Tuples is one of the important features of C#. A tuple is a data structure that contains a sequence of elements of different data types.

The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types. It can be used where you want to have a data structure to hold an object with properties, but you don't want to create a separate type for it. For example: 

  1. Tuple<int,string,string> P = new Tuple<int,string,string>(1,'sid','test');

In the above example, we've created an instance of the Tuple, which holds a record of a person. We specified a type for each element and passed values to the constructor. Specifying the type of each element is cumbersome.

C# includes a static helper class Tuple which returns an instance of the Tuple<T> without specifying the type of each element, as shown below. 
  1. var person=Tuple.Create(1,'sid','test');  
We can access the values like below.  
  1. person.item1 // this will return the 1.  
  2. person.item2 // this will return the 'Sid' string.  

A tuple can only include maximum eight elements. The compiler throws an error when you try to include more than eight elements.

In C# 7.0, Microsoft introduces the ValueTuple. it can contains more than eight elements.

ValueTuple is a structure which is a value type representation of Tuple.

To install the ValueTuple package, right click on the project in the solution explorer and select Manage NuGet Packages.

This will open the NuGet Package Manager. Click the Browse tab, search for ValueTuple in the search box and select the System.ValueTuple package, as shown below.
 
 
It is easy to create and initialize a ValueTuple. It can be created and initialized using parentheses () and specifying the values between them.

  1. var p=(1,'Sid','test');  

We can access these values like:

  1. p.item1 // return 1  
  2. p.item2 // return 'Sid'  

We can write a method like this:

  1. public (int,string,string) GetValues()  
  2. {   
  3. return (1,'Sid','Test');   
  4. }

We can assign names to a ValueTuple properties instead of having the default property names Item1, Item2 and so on

  1. (int Id,string FName,string LName) p=(1,'Sid','Test');

In this case, we can access properties like below:

  1. p.Id; // it will return 1.  
  2. p.FName; // it will return 'Sid'

Conclusion

Tuples are a powerful feature of C#. In this blog and code samples, I demostrated above how tuples can be useful in C#.