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.
C# out Keyword – Interview Questions
Q 1: What is out keyword?
Q 2: Must out variables be initialized?
Q 3: Is out parameter mandatory to assign?
Q 4: Can out pass values back to caller?
Q 5: Can out and ref be used together?
C# out Keyword – Objective Questions (MCQs)
Q1. What is the purpose of the out keyword in C#?
Q2. Which of the following must be true when using out?
Q3. Which of the following is the correct syntax for using out?
void GetValues(out int x) { x = 5; }
Q4. Can out be used with value types and reference types?
Q5. Which of the following statements is true for out parameters?