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

Following is the simple code where we are trying to initialize the salary of an employee by calling 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.

public class OutVariablesE1Old
{
    public void GetEmployeeDetails()
    {
        double salary;
        GetSalary(out salary);
    }

    private void GetSalary(out double salary)
    {
        salary = 10000;
    }
}

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. Where now it will allow to declare the variable there itself.

Following the enhanced code of above.

public class OutVariablesE1 
{ 
    public void GetEmployeeDetails() 
    { 
        GetSalary(out double salary); 
    } 

    private void GetSalary(out double salary) 
    { 
        salary = 10_000; 
    } 
}

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

public void GetEmployeeDetails() 
 { 
     GetSalary(out double salary); 
 
     if(int.TryParse(GetAge(), out int age)) 
     { 
         //Do something here 
     } 
 }

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

public void GetEmployeeDetails() 
 { 
     GetSalary(out var salary); 
     
     if(int.TryParse(GetAge(), out var age)) 
     { 
         //Do something here 
     } 
 }

Now, salary and age variable types will be set at runtime.

Hope, this explanation gives you the concept.

You can see complete code here in GitHub

Happy Coding 🙂