C#
out parameters
Learn to return multiple values from a method with out.
out parameters
The out keyword is used to return multiple values from a method. Like ref it passes by reference, but the difference is: the variable does not need to be initialized by the caller; it must be assigned inside the method.
The out keyword appears in both the declaration and the call: static void Divide(int a, int b, out int quotient, out int remainder). Call: Divide(17, 5, out int q, out int r).
ref vs out
ref and out both pass by reference but with one key difference. With ref the variable must be initialized before the call; with out it does not need to be, but it must be assigned inside the method.
Starting with C# 7, the out int r syntax lets you declare the variable at the call; there is no need to define it on a separate line beforehand. This makes the code shorter and more readable.
Exercise Divide method
Define a static void Divide(int a, int b, out int quotient, out int remainder) method; in the body assign quotient = a / b; and remainder = a % b;. In Main, call Divide(17, 5, out int q, out int r) and print q with Console.WriteLine.
Show example solution
Add quotient = a / b; and remainder = a % b; to the Divide body, write Divide(17, 5, out int q, out int r); Console.WriteLine(q); in Main.
Example solution:
using System;
class Program
{
static void Divide(int a, int b, out int quotient, out int remainder)
{
// Assign quotient and remainder
quotient = a / b;
remainder = a % b;
}
static void Main()
{
// Call Divide and print q
Divide(17, 5, out int q, out int r);
Console.WriteLine(q);
}
}
Test yourself
-
Declare out
static void Divide(int a, int b, out int quotient, ____)
{
quotient = a / b;
remainder = a % b;
}
Show answer
static void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a / b;
remainder = a % b;
}
-
Match each expression to its meaning
- out int val
- Output parameter
- out val
- out at call
- val = 5;
- Assign inside
- int val;
- Uninitialized
-
What is r after DoubleIt(5, out r)?
static void DoubleIt(int n, out int result)
{
result = n * 2;
}
DoubleIt(5, out int r);
Console.WriteLine(r);
Show answer
10 — Correct. result = 5 * 2 = 10; out writes it to r.
Next lesson: Summary - Method parameters