Working With Value Tuple In C# 7.0

I am here to continue the series related to C# 7.0 features. Today, we will be going through one of the features called Value Tuple and will demonstrate its uses in an easy way. In case you also want to go through the first part of the series, given below is the link.

Value Tuple

Value Tuple is a newly introduced type in C# 7.0 to hold finite data in a record manner. The data could be of any primitive type also it maintains the sequence of data internally.

Value tuple addresses the long pending request from developers to have some lightweight mechanism to be able to return multiple values from any method as the existing options to achieve this having some constraints as follows.

  • Out parameter
    We could achieve the multiple return values behavior using out but with below constrains.
    • The variable needs to be declared upfront along with its type (var can’t be used)
    • It can’t be used with async methods
  • Tuple
    System.Tuple is there since .NET 4.0 however it could not get popularity due to several reasons as following.

    • Tuple is a reference type with an overhead of heap and GC so it was not advisable to use for performance centric apps.
    • There was no custom naming for internal data elements so we had to use only default names as Item1, Item2 etc.
    • The syntax was verbose and also System.Tuple being a reference type, the possible null cases needs to be handled additionally.
  • Struct/class
    We could achieve the multiple return values behavior by creating class or struct however it’s an additional overhead.

    Microsoft heard this and came up with Value tuple to address the issues we had with above approaches. Additionally Value Tuple fields are public and mutable and they have value equality

Working with Value Tuple:

Now, let’s go through how to work with Value Tuple.

Please note that currently System.ValueTuple is not the part of .NET framework FCL or BCL and hence you need to get the same from nugget. The below screenshot shows the same.

C#

Once you install it, you are ready to use it. Let’s looks at the code snippets below to understand how it can be used.

  1. class ValueTupleType  
  2.     {  
  3.         //Need to get form nuget System.ValueTuple  
  4.         public static  (string, string, string, string) GetEmployeeDetail(int empId)  
  5.         {  
  6.             //Read EmployeeDetail from api, database or any other source and just return  
  7.             string firstName = "Prakash";  
  8.             string address = "Gautami enclave, Kondapur";  
  9.             string city = "Hyderabad";  
  10.             string state = "Telangana";  
  11.             return (firstName, address, city, state); // tuple literal  
  12.         }  
  13.     }  
  14.   
  15. class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             //Value Tuple, faster than Systm.Tuple<..> reference type  
  20.             int empId = 101;  
  21.             var empDetail = ValueTupleType.GetEmployeeDetail(empId);  
  22.             Console.WriteLine($"Emp detail:\n Id: {empId}\n FirstName: {empDetail.Item1}" +  
  23.                 $"\n Address: {empDetail.Item2}\n City: {empDetail.Item3}\n State: {empDetail.Item4}");  
  24.         }  
  25.     }  
Output

C#

 

So, you can see how ValueTuple can be used to pass record type data. Now let’s examine the code closely.

Th following code is a default declaration mechanism and below example tells that it will have four return values and all are of string type (although it could be any primitive type)

  1. public static  (string, string, string, string) GetEmployeeDetail(int empId)  
The problem with this kind of declaration is that while receiving the result, we will have no custom naming of fields and instead fields are named as item1, item2 etc. and hence one has to recall the sequence of fields to use them. So basically this approach gives same inflexibility as with System.Tuple
  1. Console.WriteLine($"Emp detail:\n Id: {empId}\n FirstName: {empDetail.Item1}" +  
  2.                 $"\n Address: {empDetail.Item2}\n City: {empDetail.Item3}\n State: {empDetail.Item4}");  
To address this constraint, we can use following syntax and that is one of the main advantage of System.ValueTuple.
  1. public static (string firstName, string address, string city, string state) GetEmployeeDetail(int empId)  
After declaring the tuple as above, we need not to remember the order as these fields can be retrieved by their custom names (firstName, address etc.) as following.
  1. Console.WriteLine($"Emp detail:\n Id: {empId}\n FirstName: {empDetail.firstName}" +  
  2.                $"\n Address: {empDetail.address}\n City: {empDetail.city}\n State: {empDetail.state}");  
Tuple de-construction

 

Tuple de-construction is a concept of assigning the retuned values into fresh variables and use some or all as needed.

  1. (string firstName, string address, string city, string state) = ValueTupleType.GetEmployeeDetail(empId);  
  2.   
  3. Console.WriteLine($"Emp detail:\n Id: {empId}\n FirstName: {firstName}");  
Output

C#

 

So, you can see that although we retrieved all the values but only firstName is being used.

There are some other crisp syntax available to be used in de-construction as following.

  1. (var firstName, var address, var city, var state) = ValueTupleType.GetEmployeeDetail(empId);  
Or even shorter,
  1. var (firstName, address, city, state) = ValueTupleType.GetEmployeeDetail(empId);  
Conclusion

 

In this article, we first discussed what ValueTuple is, along with examining the other available approaches followed by examples of how it can be used. In the end, we have gone through tuple de-construction and several ways to use it.

You can also download the attached demo project (ValueTupleDemo.zip) to go through the full source code referred in the article.

Hope you have liked the article. Look forward for your comments/suggestions.


Similar Articles