C Sharp Out Parameter

C# Out Parameter

To pass arguments as out-type, the out keyword is used in C#. Variable is not required in the out-type to initialize before passing. But other than that it is similar to the reference-type. It is mostly used to pass an argument as out-type and for a function to return multiple values.

Example 1:

using System;  
namespace Func_Example
{  
    class Example  
    {  
        public void Display(out int a)  
        {  
            int b = 10;  
            a = b;  
            a += a;  
            Console.WriteLine("Value inside the function: "+ a);  
        }  
        static void Main(string[] args)  
        {  
            int a = 100;  
            Example xyz = new Example(); 
            Console.WriteLine("Value before calling: "+ a);  
            xyz.Display(out a);            
            Console.WriteLine("Value after calling: " + a);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the out keyword to pass an argument as out type and the function is returning a single value.

Example 2:

using System;  
namespace Func_Example
{  
    class Example  
    {  
        public void Display(out int a, out int c)  
        {  
            int b = 10;  
            a = b;
            c = b;
            a += a;
            c += c;
        }  
        static void Main(string[] args)  
        {  
            int n1 = 100, n2 = 200;  
            Example xyz = new Example(); 
            Console.WriteLine("Value of n1 before calling: "+ n1); 
             Console.WriteLine("Value of n2 before calling: "+ n2); 
            xyz.Display(out n1, out n2);            
            Console.WriteLine("Value of n1 after calling: " + n1); 
            Console.WriteLine("Value of n2 after calling: " + n2); 
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the out keyword to pass the arguments as out type and the function is returning multiple values.