C# offers keywords as out-type for passing arguments. Only one value can be returned in a function with a return statement. But we can return two values from a function using the output parameters. Output parameters are similar to the reference parameters, with the exception that data are transferred from the method rather than into it.
Example:
using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Display(out int val) // Out parameter
{
int square = 10;
val = square;
val *= val; // Manipulating value
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val = 20;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing out variable " + val);
program.Display(out val); // Passing out argument
Console.WriteLine("Value after recieving the out variable " + val);
}
}
}
Output:
Value before passing out variable 20
Value after recieving the out variable 100
The example below shows how a function can return several values.
Example:
using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Display(out int a, out int b) // Out parameter
{
int square = 5;
a = square;
b = square;
// Manipulating value
a *= a;
b *= b;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
int val1 = 20, val2 = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing \n val1 = " + val1 + " \n val2 = " + val2);
program.Display(out val1, out val2); // Passing out argument
Console.WriteLine("Value after passing \n val1 = " + val1 + " \n val2 = " + val2);
}
}
}
Output:
Value before passing
val1 = 20
val2 = 50
Value after passing
val1 = 25
val2 = 25