Difference between ref and out? Where have you used them in your project?
Impetus · Role not specified · technical
Published
Year not specified · C#
Community answers
Posted by wasAsked editorial collection
ref requires the caller to initialize a variable before the call, and the method may read or replace it. out does not require initialization, and the method must assign it before returning.
Example:
static void AddTax(ref decimal total) => total *= 1.18m;
static bool TryRead(string text, out int value) =>
int.TryParse(text, out value);
decimal total = 100m;
AddTax(ref total);
if (TryRead("42", out var count)) { /* use count */ }
Use out for Try-pattern results. Prefer normal return values, tuples, or immutable result objects when several values must be returned; ref/out create mutation that is harder to reason about.
Backbencher Developer · · 0 likes
Both pass arguments by reference, so the method can assign to the caller's variable. The difference is about initialisation rules.
ref
- The variable must be initialised before it is passed.
- The method may read and modify it (but does not have to assign it).
- Used when the method needs the current value and may update it.
out
- The variable does not need to be initialised before the call.
- The method must assign it before returning; it cannot read it before assigning.
- Used to return additional values from a method.
Examples:
void ApplyDiscount(ref decimal price, decimal percent) => price -= price * percent / 100;
decimal total = 1000m;
ApplyDiscount(ref total, 10); // total is now 900
bool TryParseOrderId(string input, out int orderId)
{
orderId = 0;
if (input.StartsWith("ORD-") && int.TryParse(input[4..], out var id)) { orderId = id; return true; }
return false;
}
if (TryParseOrderId(code, out var orderId)) { /* use orderId */ } // inline declaration (C# 7)
Where I used them in projects
- out: the TryXxx pattern everywhere — int.TryParse, Dictionary.TryGetValue, Enum.TryParse, and my own TryGetFromCache(key, out value) methods to avoid exceptions for expected failures.
- ref: performance-sensitive code with large structs, to avoid copying (ref and the read-only variants in and ref readonly), and when working with Span<T> and ref locals or returns. Also rare cases like Interlocked.Increment(ref counter) and swapping values.
Related modifiers
- in (C# 7.2): passes by reference but read-only — useful for large structs.
- ref readonly parameters (C# 12) for clearer intent.
- Async methods and iterators cannot have ref or out parameters; return a tuple or result object instead.
Design advice
For returning several values, modern C# often prefers tuples or records — (bool Success, int OrderId) or a Result<T> type — which are clearer than multiple out parameters. Reserve out for the established TryXxx pattern and ref for real performance needs.