Share via


C# 7.0 : Out Parameter

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.

In-line declaration of Out parameter

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:

using System;  
using static  System.Console;  
   
namespace OutExample  
{  
    class Program  
    {  
        static void  Main(string[] args)  
        {  
            WriteLine("Please enter radius for circle");  
            double radius = Convert.ToDouble(ReadLine());  
            double circumference = CalculateCircle(radius, out double  area);  
            WriteLine($"Circle's circumference is {circumference}");  
            WriteLine($"Circle's Area is {area}");  
            ReadKey();  
        }  
   
       static double  CalculateCircle(double radius, out double  area)  
        {  
            area = Math.PI * Math.Pow(radius, 2);  
            double circumference = 2 * Math.PI * radius;  
            return circumference;  
        }  
    }  
}

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

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.

    double circumference = CalculateCircle(radius, out double  area);
    

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

  3. The in-line declared Out parameter can be accessed in the same block. Its scope is in the method where it calls.

  4. The called method is required to assign a value to Out parameter before the method returns.

  5. The method can be overloaded based on Out parameters.

  6. Async methods don’t have out parameter.

  7. Iterator methods don’t have out parameter.

Implicit 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.

using static  System.Console;  
   
namespace OutExample  
{  
    class Program  
    {  
        static void  Main(string[] args)  
        {  
            int [] arr = { 1, 56, 58, 57, 90, 92, 94, 93, 91, 45 };   
            int n = arr.Length;  
            findLength(arr, n, out  var maxlenth);  
            WriteLine($"Length of the longest contiguous subarray is {maxlenth}");             
            ReadKey();  
        }  
   
        static void  findLength(int  []arr,  int  n, out  int maxlength)  
        {  
            maxlength = 1;    
            for (int i = 0; i < n - 1; i++)  
            {                  
                int mn = arr[i], mx = arr[i];                  
                for (int j = i + 1; j < n; j++)  
                {                     
                    mn = min(mn, arr[j]);  
                    mx = max(mx, arr[j]);                      
                    if ((mx - mn) == j - i)  
                    {  
                        maxlength = max(maxlength, mx - mn + 1);  
                    }                          
                }  
            }             
        }  
        static int  min(int  x, int  y)  
        {  
            return (x < y) ? x : y;  
        }  
        static int  max(int  x, int  y)  
        {  
            return (x > y) ? x : y;  
        }  
    }  
}

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

Figure 2: Output

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

Use in Try Pattern

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.

using static  System.Console;  
   
namespace OutExample  
{  
    class Program  
    {  
        static void  Main(string[] args)  
        {  
            WriteLine("Please enter you age");  
            bool isValid = int.TryParse(ReadLine(), out  int age);  
            string message = isValid ? $"You are {age} Years old" : "Please enter valid age";  
            WriteLine(message);             
            ReadKey();  
        }         
    }  
}

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.

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.

See Also

There are some more article related C#. These are:

  1. C# 7 : Func, Action And Local Function
  2. C# 7 : Tuple
  3. C# : Why Use Property
  4. C#: Dependency Injection In Console Application