In C#, both ref and out are used to pass arguments by reference to a method, but they differ in terms of
initialization requirements and intended purpose.
Key Differences
Feature
ref
out
Initialization before call
✅ Must be initialized
❌ Doesn't have to be initialized
Must be assigned in method
❌ Not required (but allowed)
✅ Must be assigned before return
Purpose
Pass value in and out
Return additional output from method
Common use
Modify an existing variable
Return multiple values
ref Example
void Update(ref int number)
{
number += 10;
}
int x = 5;
Update(ref x); // x becomes 15
Must initialize x before passing
Can read and write x inside the method
out Example
void GetValues(out int a, out int b)
{
a = 10;
b = 20;
}
int x, y;
GetValues(out x, out y); // x = 10, y = 20
x and y don’t need initialization before the call
They must be assigned inside the method
Compile-Time Rules
Check
ref
out
Must be assigned before method
✅
❌
Must be assigned in method
❌
✅
Must use keyword when calling
✅
✅
When to Use What?
Use Case
Recommended
Modify input and return value
ref
Return multiple values from a method
out
Passing large structs efficiently
ref
Bonus: ref readonly
You can also use ref readonly to pass by reference without allowing modification.
void PrintValue(ref readonly int value)
{
Console.WriteLine(value);
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, both
refandoutare used to pass arguments by reference to a method, but they differ in terms of initialization requirements and intended purpose.Key Differences
refoutrefExamplexbefore passingxinside the methodoutExamplexandydon’t need initialization before the callCompile-Time Rules
refoutWhen to Use What?
refoutrefBonus:
ref readonlyYou can also use
ref readonlyto pass by reference without allowing modification.