What is the difference between ref and out parameters?
Quick Answer
Both pass an argument by reference so the method can modify the caller's variable. ref requires the variable to be initialised before the call and the method may read it. out does not require initialisation and the method must assign it before returning. in is the read-only counterpart — passed by reference, cannot be modified.
Both pass by reference so the method can change the caller's variable. With ref, the variable has to be initialised before you pass it, and the method can both read and write it. With out, it doesn't need to be initialised, but the method is required to assign it before it returns — that's why TryParse uses out. There's also in, which is pass-by-reference but read-only, mainly used to avoid copying a big struct. These days I'd often just return a tuple instead of using several out parameters.
| ref | out | in | |
|---|---|---|---|
| Init before call | Required | Not required | Required |
| Method must assign | No | Yes, before returning | Cannot assign |
| Direction | In and out | Out only | In only (read-only ref) |
| Typical use | Swap, in-place update | TryParse, returning multiple values | Pass a large struct without copying |
Modern C# often replaces multiple out parameters with tuples ((bool ok, int value)) or a result type. out var declares the variable inline: if (int.TryParse(s, out var n)).
// out: no init needed, method must assign
if (int.TryParse(input, out var value))
Console.WriteLine(value * 2);
// ref: must init first, method reads and writes
int a = 1, b = 2;
void Swap(ref int x, ref int y) { (x, y) = (y, x); }
Swap(ref a, ref b); // a == 2, b == 1