C# 7 Features - Tuples

In order to return multiple values from a method in C#, we can use approaches like creating out parameters, creating a custom class with the required properties, or using tuples. 
 
However, in C# 7.0, we have the concept of tuples (quite similar to existing tuples), which can help in returning multiple values from a method.
 
Suppose we have a method, which will return the Department and Age of an employee, based on the EmployeeID. Using the old ways, we could have two out parameters for department and age, along with the EmployeeID, or create a custom class of an employee type and return the values or even use the existing tuple types. However, with new features, we can have a method with two return type values; i.e., int age and string department. The signature of the method would look, as shown below.
  1. public static (intstring) GetEmployeeById(int employeeId)  
  2.        {  
  3.            int empAge = 32;  
  4.            string dept = "HR";  
  5.            return (empAge, dept);  
  6.        }   
After calling the method, we can access the return values, as shown below.
  1. var employeeDetails = GetEmployeeById(21);  
  2. Console.Write("Age is: " + employeeDetails.Item1+ ", Department is:" + employeeDetails.Item2);   
The code does not seem to be too user friendly here, as we have to use the keywords Item1, Item2 etc. (similar to the existing tuples concept). However, we can change our method signature to include the use of names for the return values. Hence, the code will change to what is shown below.
  1. public static (int age, string department) GetEmployeeById(int employeeId)    
  2.        {    
  3.            int empAge = 32;    
  4.            string dept = "HR";    
  5.            return (empAge, dept);    
  6.        }    
Now, in order to access the elements, our code will change to what is shown below.
  1. var employeeDetails = GetEmployeeById(21);    
  2. Console.Write("Age is: " + employeeDetails.age + ", Department is:" + employeeDetails.department);    
There is another way to catch the returned values, which uses another new feature named deconstruction. We will learn about this in our next document. Hence, this was about the concept of tuples in C# 7.0. I hope you enjoyed reading it. Happy coding...!!! 

Up Next
    Ebook Download
    View all
    Learn
    View all