ref and out Parameters
ref and out let a method work directly with your original variable instead of a copy, like lending your actual notebook instead of a photocopy. With out, the method must fill the answer in for you.
In this page:
Syntax
static void MethodName(ref type parameter) // read and modify caller's variable
{
}
static bool TryMethod(type input, out type result) // must assign result
{
result = value;
return true;
}
MethodName(ref variable);
TryMethod(input, out type result);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the
reforoutkeyword at the call site, which is a compile error. - Passing an uninitialized variable to
ref, whenrefneeds an initialized variable andoutdoes not. - Not assigning an
outparameter in every code path of the method, which is a compile error.
Chapter Summary
- Methods group reusable code with parameters and return types.
- Method overloading and optional parameters make methods flexible.
refandoutparameters pass values by reference or return extra results.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: