Letβs clarify the difference between ref and out in C# β two ways to pass variables by reference
π 1. What They Do
Both ref and out allow a method to modify the callerβs variable directly, instead of working on a copy.
-
ref β the variable must be initialized before passing.
-
out β the variable does not need to be initialized, but must be assigned inside the method.
π 2. ref Example
void Increment(ref int x)
{
x += 1;
}
int number = 5;
Increment(ref number);
Console.WriteLine(number); // Output: 6Key Points:
-
numbermust be initialized before passing. -
Changes inside the method affect the original variable.
π 3. out Example
void GetValues(out int a, out int b)
{
a = 10; // Must assign inside method
b = 20; // Must assign inside method
}
int x, y; // Not initialized
GetValues(out x, out y);
Console.WriteLine($"{x}, {y}"); // Output: 10, 20Key Points:
-
xandydo not need initialization before passing. -
Method must assign a value to all out parameters before returning.
π 4. Differences Table
| Feature | ref | out |
|---|---|---|
| Initialization required | Must be initialized before passing | No, can be uninitialized |
| Assignment inside method | Optional | Mandatory |
| Purpose | Pass value by reference, can read & modify | Pass value by reference, method must provide value |
| Common usage | Modify existing value | Return multiple values, output results |
π 5. Combined Example
void Calculate(ref int num, out int square)
{
num += 5; // modifies original num
square = num * num; // must assign square
}
int number = 3;
int result;
Calculate(ref number, out result);
Console.WriteLine(number); // 8
Console.WriteLine(result); // 64-
refreads & modifiesnumber -
outmust be assignedresult
β Tip:
-
Use
refwhen you want to modify an existing value. -
Use
outwhen you want a method to return multiple values without initializing them first.