What is the difference between ref and out parameters in C#?

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

Quick Answer

Both pass by reference. ref — the variable must be initialised before the call; the method may read and write it. out — the variable needn't be initialised; the method must assign it before returning. out signals “this is an additional output”, as in the TryParse pattern.

Both make the parameter a reference to the caller's variable rather than a copy. The difference is the contract: with ref the caller has to initialise the variable first, and the method can both read and change it. With out the caller doesn't need to initialise it, but the method is required to assign it before it returns. out is really for “return an extra value” — that's the TryParse pattern, where the return is the success bool and the parsed value comes back through out. There's also in, which is by-reference but read-only, used to avoid copying big structs.

  • if (int.TryParse(s, out var n)) { ... } — inline out var declaration since C# 7.
  • in is the third variant — pass by reference but read-only, an optimization for large structs.
  • For multiple results, a tuple return ((bool ok, int value)) is often cleaner than out.
  • You can't use ref/out/in with async methods or iterators.