The out keyword is also used to pass parameters by reference, but it is specifically used when the method is expected to return a value through the parameter. The key difference is that you don’t need to initialize the variable before passing it to the method. However, the method must assign a value to the out parameter before it exits.
Characteristics of out keyword
1. No Initialization Required: The variable does not need to be initialized before passing it to the method.
2. Must Be Assigned Inside Method: The method must assign a value to the out parameter before the method ends. You cannot leave the out parameter unassigned.
3. Used for Returning Multiple Values: It’s typically used when you need a method to return more than one value or a value when the result is uncertain (e.g., for TryParse methods).
Example:
using System;
class Calaculator
{
public void getSum(int a, int b, out int sum)
{
sum = a + b; // Assign a value to the out parameter
}
public void getSumAndProduct(int a, int b, out int totalSum, out int product)
{
totalSum = a + b; // Assign a value to the out parameter
product = a * b; // Assign a value to the out parameter
}
}
class MyExample
{
static void Main(string[] args)
{
int sum, totalSum, product;
Calaculator cal = new Calaculator();
// Pass variables by reference using 'out'
cal.getSum(5, 10, out sum);
cal.getSumAndProduct(5, 10, out totalSum, out product);
Console.WriteLine("Sum: " + sum); // Output: Sum: 15
Console.WriteLine("totalSum: " + totalSum); // Output: totalSum: 15
Console.WriteLine("product: " + product); // Output: product: 50
}
}
Output:
totalSum: 15
product: 50
Explanation:
- The sum, totalSum and product parameters are passed by reference using the out keyword.
- The method assigns values to sum, totalSum and product, and these values are reflected outside the method.