Example: out Parameter
void GetValues(out int a)
{
a = 10; // Must assign inside the method
}
int number; // Not initialized
GetValues(out number);
Console.WriteLine(number); // 10-
Notice
numberwas never given a value beforeGetValueswas called. -
Inside
GetValues, the value must be assigned (a = 10). -
After the call,
numbernow holds10.
Contrast with ref
void Increment(ref int x)
{
x += 5;
}
int number; // Not initialized
Increment(ref number); // ❌ Error: must initialize before passing-
refrequires that the variable already has a value before calling the method. -
The method can then read and modify it.
Key Idea
-
out→ method is responsible for giving the variable a value; the caller doesn’t have to set it first. -
ref→ caller must set the variable first; method can then read and modify it.