In C#, how do ref and out parameters differ, and what does the compiler require of the caller and of the called method?
answer
- who assigns, and when
- definite assignment on both sides
- unassigned local passed by ref
- every returning path writes it
- out var and out _
basics
~20 sBoth pass the caller's variable by reference. A ref argument must be assigned before the call, and the method may read or change it; an out argument may be unassigned, and the method must assign it on every path that returns.
solid answer
~40 sBoth `ref` and `out` make the parameter an alias for a variable the caller owns, so a write inside the method lands in that variable at once, and both need the modifier at the call site too. They differ in **definite assignment**. A `ref` argument must be assigned before the call (otherwise CS0165), and the method may read it, write it or leave it alone. An `out` argument may be unassigned: the method cannot read it before writing it (CS0269) and must assign it on every path that returns (CS0177). That makes `out` the shape of the Try pattern, `int.TryParse(string? s, out int result)`, usually called with `out var n` to declare the variable inline or `out _` to discard it. Two overloads that differ only by `ref` versus `out` are rejected with CS0663.
code
csharp · 35 lines// out vs ref: a TryParsePoint helper
string[] inputs = ["3,4", "x,1"];
foreach (var text in inputs)
{
if (Geometry.TryParsePoint(text, out var p))
Console.WriteLine($"{text} -> ({p.X}, {p.Y})");
else
Console.WriteLine($"{text} -> invalid, p = ({p.X}, {p.Y})");
}
bool ok = Geometry.TryParsePoint("7,8", out _); // discard: only the bool matters
Console.WriteLine($"discard call: {ok}");
int offset = 10; // ref needs an initialized variable
Geometry.Shift(ref offset);
Console.WriteLine($"offset = {offset}");
public readonly record struct Point(int X, int Y);
public static class Geometry
{
public static bool TryParsePoint(string text, out Point point)
{
var parts = text.Split(',');
if (parts.Length == 2 && int.TryParse(parts[0], out int x) && int.TryParse(parts[1], out int y))
{
point = new Point(x, y);
return true;
}
point = default; // every return path must assign point
return false;
}
public static void Shift(ref int value) => value += 5;
}go deeper
Recall the two-sided contract: ref needs an assigned argument and lets the method read it, out needs the method to assign it before returning. Know out var and the out _ discard.
Explain definite assignment on both sides and the errors it produces, CS0165, CS0269 and CS0177, and why a Try method assigns default to its out parameter on failure.
Show judgment about when a by-reference parameter is worth it compared with returning a tuple or a record, and mention that it rules a method out of async and iterator use.
Treat the Try pattern as an API convention a team keeps consistent, and keep ref parameters out of public APIs unless the caller's variable genuinely has to change.
## Passing by value, passing by reference By default C# passes every argument **by value**: the parameter is a new variable initialised with a copy of the argument. For a `struct` that is a copy of the data; for a `class` it is a copy of the reference, so both variables point at the same object. A **by-reference parameter** is different: it has no storage of its own. It is an *alias* for a variable the caller owns, and every read or write goes straight to that variable. C# has four modifiers that make a parameter by-reference (`ref`, `out`, `in` and `ref readonly`), and `ref` and `out` are the two every C# developer uses. Because the alias is live, a write is visible in the caller's variable the moment it happens. There is no copy-in, copy-out step at the end of the call. ## What each side must do The difference between `ref` and `out` is not the mechanism (both pass a reference to a variable) but the **definite-assignment contract** the compiler enforces on each side of the call. | | `ref` | `out` | |---|---|---| | Call-site modifier | required: `Shift(ref offset)` | required: `TryParsePoint(text, out var p)` | | Argument before the call | must be definitely assigned | may be unassigned | | Reading inside the method | allowed at once | only after the method has assigned it | | Assigning inside the method | optional | required on every path that returns | | Typical intent | read my variable and maybe update it | produce an extra result | Each broken rule is a compile-time error, not a run-time check: - **CS0165**, *Use of unassigned local variable*: the caller passed an unassigned local with `ref`. C# demands definite assignment of locals however the runtime initialises stack memory. - **CS0269**, *Use of unassigned out parameter*: the method read an `out` parameter before writing it. Whatever the variable held before the call is treated as unassigned. - **CS0177**, *The out parameter must be assigned to before control leaves the current method*: some `return` path skips the assignment. A path that ends in `throw` needs no assignment, because it never returns normally and the caller never reads the variable. ## The Try pattern, out var and discards `out` exists mainly for methods that return a success flag plus a value, which is the BCL's **Try pattern**: `int.TryParse(string? s, out int result)` and `Dictionary<TKey,TValue>.TryGetValue(TKey key, out TValue value)`. A geometry helper follows the same shape: ```csharp public static bool TryParsePoint(string text, out Point point) { // ... on success: point = new Point(x, y); return true; point = default; // the failure path must assign too return false; } ``` Two call-site features make these methods pleasant to use: 1. **`out var`** declares the variable inside the argument list: `if (Geometry.TryParsePoint(text, out var p)) ...`. A variable declared this way in an `if` condition stays in scope for the rest of the enclosing block, so `if (!int.TryParse(s, out var n)) return;` followed by a use of `n` compiles. 2. **`out _`** is a discard. The method still writes its result somewhere, but the caller gets no variable, which is the honest way to say that only the `bool` matters. By convention a Try method assigns `default` to its `out` parameter on failure, and callers do not rely on that value. ## Signatures and overloading The modifiers are part of a method's C# signature, so `Save(int x)` and `Save(ref int x)` can coexist as overloads: the call site's `ref` picks the second one. But for overloading C# treats `ref`, `out`, `in` and `ref readonly` as the same kind of parameter, since all four pass a reference, so two members that differ *only* in which of these modifiers they use are rejected with **CS0663**, *cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref'*. The call-site modifier is not decoration either. It must match the declaration, and a `ref` or `out` argument has to be a variable (a local, a parameter, a field or an array element), not a property, an indexer result or a literal. ## Choosing between them - Use **`out`** when the method's job is to produce a value the caller does not have yet: the Try pattern, or a second result where a return tuple would be awkward. - Use **`ref`** when the method must read the caller's current value and may replace it: `Interlocked.Increment(ref int location)`, swapping two variables, advancing a cursor held by the caller. - Prefer a **return value**, a tuple or a small record when neither applies. By-reference parameters make the data flow harder to follow at the call site, cannot take properties as arguments, and are not allowed in `async` methods or iterators at all.
- Can a C# class overload Save(ref int x) with Save(out int x)?No. Members cannot differ only by `ref`, `out`, `in` or `ref readonly`, because all four are passed as a reference; the compiler reports CS0663. You can overload a by-value parameter against a by-reference one, such as `Save(int x)` and `Save(ref int x)`, and the call-site modifier then picks between them.
- Where is a variable declared with out var inside an if condition in scope?In the whole enclosing block, not just the `if` statement. That is what makes the guard style work: `if (!int.TryParse(input, out var n)) return;` and then use `n` on the next line. Definite assignment is satisfied because `TryParse` assigns `n` on every path that returns.
- Does a method have to assign its out parameter on a path that throws?No. CS0177 applies to paths that return normally; a path that ends in `throw` never hands control back, so the caller cannot read the variable. Every path that does return, including the failure path of a Try method, must assign it, usually with `default`.
- An out argument must be initialised by the caller before the call.
- A method with a ref parameter must assign it before it returns.
- ref copies the value in and copies the result back when the method returns.
- A method may read an out parameter's incoming value before setting it.
- Save(ref int) and Save(out int) are valid overloads because the call site shows which one.