Out Variable Enhancements In C# 7.0

In C# 7.0, there were a couple of improvements in using the Out variable. To understand these enhancements, we need to know how it was implemented in earlier versions, i.e., before C# 6.0. 

Following is the simple code where we are trying to initialize the salary of an employee by calling the GetSalary method. To do this, we are accepting an out parameter to this method. If you declare a parameter as Out, a method cannot be returned without initiating or assigning any value to this variable. So, we expect a guaranteed value assigned once this method returns. 

  1. public class OutVariablesE1Old {  
  2.     public void GetEmployeeDetails() {  
  3.         double salary;  
  4.         GetSalary(out salary);  
  5.     }  
  6.     private void GetSalary(out double salary) {  
  7.         salary = 10000;  
  8.     }  

Everything looks good, but as observed, do we really need two lines of code in GetEmployeeDetails() method? No, why can't we club both into a single line? Yes exactly, this is the first enhancement in C# 7.0. Now, it allows to declare the variable there itself.

 Following is the enhanced code of the above scenario. 

  1. public class OutVariablesE1 {  
  2.     public void GetEmployeeDetails() {  
  3.         GetSalary(out double salary);  
  4.     }  
  5.     private void GetSalary(out double salary) {  
  6.         salary = 10 _000;  
  7.     }  

As you can see in the above code, we declared the salary variable while calling the method. This will improve more readability and decrease the junk lines of code. Similarly, we can use it in try... methods.

  1. public void GetEmployeeDetails() {  
  2.     GetSalary(out double salary);  
  3.     if (int.TryParse(GetAge(), out int age)) {  
  4.         //Do something here   
  5.     }  
  6. }  

Now, everything looks good. But, let's say, our GetSalary() method implementation is in some other third party component and we are not sure what type of data it is assigning to our variable. In such a case, instead of providing predefined data type, we can send a var variable as below. Well, this is our another enhancement in C# 7.0. 

  1. public void GetEmployeeDetails() {  
  2.     GetSalary(out  
  3.         var salary);  
  4.     if (int.TryParse(GetAge(), out  
  5.             var age)) {  
  6.         //Do something here   
  7.     }  
  8. }  

Now, the salary and age variable types will be set at runtime. Hope this explanation clarifies the concept. 

You can see the complete code here on GitHub.

Happy Coding :) 

Next Recommended Reading C# 7.0 New Feature - Tuples In C# 7