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.
- 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. Now, it allows to declare the variable there itself.
Following is the enhanced code of the above scenario.
- public class OutVariablesE1 {
- public void GetEmployeeDetails() {
- GetSalary(out double salary);
- }
- private void GetSalary(out double salary) {
- salary = 10 _000;
- }
- }
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.
- public void GetEmployeeDetails() {
- GetSalary(out double salary);
- if (int.TryParse(GetAge(), out int age)) {
-
- }
- }
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.
- public void GetEmployeeDetails() {
- GetSalary(out
- var salary);
- if (int.TryParse(GetAge(), out
- var age)) {
-
- }
- }
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 :)