Out Parameter In C# 7

Introduction

This article introduces new features of the Out parameter in C# 7.0. The Out parameter is used when a method returns multiple values. When a parameter passes with the Out keyword/parameter in the method, then that method works with the same variable value that is passed in the method call. If variable value changes, the method parameter value also changes.

There are some additional features for Out parameter
  1. Out parameter can pass without its declaration and initialization.
  2. Out parameter can use var type in the method parameter list.
  3. It is not obligatory that Out parameter name should be same in both function definition and call.
This article elaborates about improved features of Out parameter with the help of examples. So, let’s see each one by one.
 
What's New in C# 7
 
 
In-line declaration of Out paramater

In the earlier C# versions, we would need to separate the declaration and initialization of the Out variable into two different statements. C# 7.0 provides this feature that the Out parameter can pass without its declaration and initialization. Let’s see an example.

  1. using System;  
  2. using static System.Console;  
  3.   
  4. namespace OutExample  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             WriteLine("Please enter radious for circle");  
  11.             double radious = Convert.ToDouble(ReadLine());  
  12.             double circumference = CalculateCircle(radious, out double area);  
  13.             WriteLine($"Circle's circumference is {circumference}");  
  14.             WriteLine($"Circle's Area is {area}");  
  15.             ReadKey();  
  16.         }  
  17.   
  18.        static double CalculateCircle(double radious, out double area)  
  19.         {  
  20.             area = Math.PI * Math.Pow(radious, 2);  
  21.             double circumference = 2 * Math.PI * radious;  
  22.             return circumference;  
  23.         }  
  24.     }  
  25. }   

Now, run this program. The result shows as per the following figure.

Output
Figure 1: Output

This code shows the following features about Out parameter.

  1. A method can have one or more than one Out parameter.
  2. When using a method which has Out parameter, you don’t need to declare and initialize that Out parameter before.

     

    1. double circumference = CalculateCircle(radious, out double area);  

    The Out parameter can declare in-line at the time of method call such as area parameter.

  1. The in-line declared Out parameter can be accessed in the same block. Its scope is in the method where it calls.
  2. The called method is required to assign a value to Out parameter before the method returns.
  3. The method can be overloaded based on Out parameters.
  4. Async methods don’t have out parameter.
  5. Iterator methods don’t have out parameter.
Implict Type Out Parameter

As shown in the example, the Out parameter is declared with specifying type in the parameter list for clarity. However, the language does support using an implicitly typed local variable. The data type of a var variable will be determined when assigning a value to the variable. After assigning the variable value, the variable has a defined data type and cannot be replaced.

As var type variable has local scope (means scope in the method body), similarly, in-line Out parameter has scope in method body that’s why var type can also be used as Out parameter.

Let’s create an example. Find the length of the longest subarray which contains numbers that can be arranged in a continuous sequence from an integer array. 

  1. using static System.Console;  
  2.   
  3. namespace OutExample  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             int [] arr = { 1, 56, 58, 57, 90, 92, 94, 93, 91, 45 };  
  10.             int n = arr.Length;  
  11.             findLength(arr, n, out var maxlenth);  
  12.             WriteLine($"Length of the longest contiguous subarray is {maxlenth}");             
  13.             ReadKey();  
  14.         }  
  15.   
  16.         static void findLength(int []arr,  int n, out int maxlength)  
  17.         {  
  18.             maxlength = 1;    
  19.             for (int i = 0; i < n - 1; i++)  
  20.             {                  
  21.                 int mn = arr[i], mx = arr[i];                  
  22.                 for (int j = i + 1; j < n; j++)  
  23.                 {                     
  24.                     mn = min(mn, arr[j]);  
  25.                     mx = max(mx, arr[j]);                      
  26.                     if ((mx - mn) == j - i)  
  27.                     {  
  28.                         maxlength = max(maxlength, mx - mn + 1);  
  29.                     }                          
  30.                 }  
  31.             }             
  32.         }  
  33.         static int min(int x, int y)  
  34.         {  
  35.             return (x < y) ? x : y;  
  36.         }  
  37.         static int max(int x, int y)  
  38.         {  
  39.             return (x > y) ? x : y;  
  40.         }  
  41.     }  
  42. }   

Now, run this program. The result shows as per the following figure.

Output
Figure 2: Output

As shown in above program, Out parameter can be an implicit type. Use in Try Pattren

The Out parameter is mostly used in the Try-pattern. In this pattern, a method returns a bool indicating success or failure and an Out variable that provides the result if the method succeeds. Let’s see an example for same. This example shows that user enters value. If the value is valid integer, then it shows result. 

  1. using static System.Console;  
  2.   
  3. namespace OutExample  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             WriteLine("Please enter you age");  
  10.             bool isValid = int.TryParse(ReadLine(), out int age);  
  11.             string message = isValid ? $"You are {age} Years old" : "Please enter valid age";  
  12.             WriteLine(message);             
  13.             ReadKey();  
  14.         }         
  15.     }  
  16. }   

As shown in above code, try pattern method assigns value in Out parameter if it succeeded. Now, run this program and the result shows as per the following figure.

Output
Figure 3: Output

Conclusion

The Out parameter features are improved in C# 7.0. Both in-line and implicit type declaration are new in this new version.

Up Next
    Ebook Download
    View all
    Learn
    View all