ref and out Parameters
In this page:
ref and out Parameters
ref passes a variable by reference so the method can read and modify the caller's original value; the variable must already be initialized. out also passes by reference but is meant for methods that assign a value the method didn't receive, like TryParse. Both require the ref/out keyword at both the declaration and the call site.
Warning: An out parameter must be assigned inside the method before it returns, or the compiler rejects the code.
Example: ref and out Parameters
using System;
class Program
{
static void Double(ref int x)
{
x = x * 2;
}
static bool TryDivide(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false;
}
result = a / b;
return true;
}
static void Main(string[] args)
{
int n = 5;
Double(ref n);
Console.WriteLine(n);
if (TryDivide(10, 2, out int quotient))
Console.WriteLine(quotient);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: