What is the difference between ref and out parameters?

C# Methods & Parameters Basic Fresher1–2 Yrs Conceptual 1 min read

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.

refoutin
Init before callRequiredNot requiredRequired
Method must assignNoYes, before returningCannot assign
DirectionIn and outOut onlyIn only (read-only ref)
Typical useSwap, in-place updateTryParse, returning multiple valuesPass 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)).

C# — out with TryParse
// 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