1.18 — Tuples, Deconstruction, ref / out / in¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.17 Pattern matching · Next: 1.19 Indexers and operators
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- A tuple lets a method return several values without declaring a class:
(bool ok, string error). out= the method must assign it.ref= it must already have a value, and the method can change it.in= pass by reference but read-only.- Tuples are great inside your code. Do not use them on a public API — named types document themselves.
The concept¶
A method can only return one thing. But sometimes you genuinely have two answers: "did it work, and if so what is the result?"
There are four ways to handle that, and knowing when each fits is the point of this topic:
- Return a tuple — quick, no ceremony
- Use an
outparameter — the classicTryParsestyle - Return a small
record— clearest for anything public - Return a Result type — best when failure carries information
How it works¶
Tuples¶
// Returning two values with no class needed
public (bool Success, string? Error) Validate(Order order)
{
if (order.Total <= 0)
return (false, "Total must be positive");
return (true, null);
}
Using it:
Notice you get real names — Success and Error, not Item1 and Item2. Naming the
elements in the return type is what makes tuples readable. Without names you get:
public (bool, string?) Validate(Order o) { ... }
var r = Validate(order);
if (!r.Item1) Console.WriteLine(r.Item2); // what are these? Unreadable.
Always name your tuple elements.
Deconstruction¶
You can split a tuple straight into separate variables:
Or discard the parts you do not need with _:
Records get deconstruction for free (1.2), and you can add
it to any class by writing a Deconstruct method:
public class Point(int x, int y)
{
public void Deconstruct(out int x2, out int y2) { x2 = x; y2 = y; }
}
var (x, y) = new Point(3, 4);
Deconstruction also works nicely with dictionaries:
out — the method must fill it in¶
if (int.TryParse(input, out int number))
Console.WriteLine(number * 2);
else
Console.WriteLine("Not a number");
Rules for out:
- The caller does not need to initialise it beforehand.
- The method must assign it before returning, on every path. The compiler enforces this.
- You can declare the variable inline, as above, which is the modern style.
The Try... pattern is the standard use: return a bool for success, put the actual value
in an out parameter. It is used everywhere in .NET —
int.TryParse, dictionary.TryGetValue, DateTime.TryParseExact.
You can discard an out you do not care about:
ref — pass the variable itself¶
Rules for ref:
- The variable must already have a value before the call.
- The method may read it and change it.
- You must write
refat both the declaration and the call site.
That last rule is deliberate. Because ref means "this method might change my variable",
C# forces you to write it at the call site so the reader can see it happening.
ref is rarely needed in everyday code. Its main modern uses are performance work with
large structs, and interop with non-.NET code.
in — pass by reference, but read-only¶
static double Distance(in Point a, in Point b)
{
// a and b cannot be modified here — the compiler enforces it
return Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
}
in exists purely for performance with large structs. Normally passing a struct copies
the whole thing. in passes a reference instead, avoiding the copy, while still promising
the method will not modify it.
For a small struct it is not worth it — the reference is about the same size as the value.
It only pays off once the struct is bigger than roughly 16–24 bytes. And it works best with
readonly struct, because otherwise the compiler sometimes has to make a defensive copy
anyway, which defeats the purpose.
Quick comparison¶
| Must be initialised before? | Can the method change it? | Write keyword at call site? | |
|---|---|---|---|
out |
No | Must assign it | Yes |
ref |
Yes | Yes | Yes |
in |
Yes | No | Optional |
Code¶
Choosing between the approaches — this is what an interviewer is really testing:
// TUPLE — fine for a private helper, quick and readable
private (decimal Subtotal, decimal Tax) CalculateTotals(Order order)
{
var subtotal = order.Lines.Sum(l => l.Price * l.Quantity);
return (subtotal, subtotal * 0.2m);
}
// OUT — right when the caller often does not want the value at all
public bool TryGetDiscount(string code, out decimal discount)
{
discount = 0;
if (!_codes.TryGetValue(code, out var found)) return false;
discount = found;
return true;
}
// RECORD — right for anything public. It documents itself
// and you can add a field later without breaking callers.
public record OrderTotals(decimal Subtotal, decimal Tax, decimal Total);
public OrderTotals CalculateTotals(Order order) { ... }
// RESULT TYPE — right when failure carries real information
public Result<Order> PlaceOrder(CreateOrderRequest request) { ... }
The rule of thumb: tuples inside a class, named types across a public boundary. A tuple in a public API forces every caller to remember what the elements mean, and adding a third element is a breaking change.
Interview questions¶
Q: When would you use a tuple instead of a class?
For a private or internal method that genuinely needs to return two or three related values,
where creating a whole type would be more ceremony than it is worth. They are quick, they
are allocated on the stack since ValueTuple is a struct, and with named elements they read
well. But I would not put one on a public API — a named record documents itself, shows up
properly in IntelliSense and Swagger, and can gain a property later without breaking
callers.
Q: What is the difference between ref and out?
With out, the caller does not have to initialise the variable, but the method is required
to assign it before returning — the compiler checks every path. With ref, the variable
must already have a value, and the method may read it as well as change it. So out is for
"the method gives me a value", and ref is for "the method modifies my existing value".
Both require the keyword at the call site so the reader can see that a variable may be
changed.
Q: What is in for?
Passing a value type by reference without allowing modification. It exists for performance —
a large struct normally gets copied on every call, and in avoids that copy while still
guaranteeing the method will not change it. It is only worth using for structs bigger than
around 16 to 24 bytes, and it works best with a readonly struct, because otherwise the
compiler may make a defensive copy anyway and you gain nothing.
Q: Are tuples value types or reference types?
The modern ones are value types. ValueTuple, which is what the (int, string) syntax
creates, is a struct, so it is generally allocated without hitting the heap. The older
System.Tuple class is a reference type and is mostly obsolete now. Worth knowing that
ValueTuple is mutable and compares by value.
Traps ⚠️¶
- Unnamed tuple elements give you
Item1andItem2. Unreadable. Always name them. - Tuple element names are not part of the runtime type. They are compiler metadata, so
reflection and some serializers see only
Item1/Item2. - Tuples in public APIs age badly. Adding an element is a breaking change, and they serialize poorly.
ValueTupleis mutable. Unlike a record, you can change its fields, which is occasionally surprising.outparameters cannot be used in async methods. This is a common annoyance — use a tuple or a small result type instead.incan be slower for small structs, because passing a reference and then reading through it costs more than just copying a few bytes.- A
reforoutparameter cannot be captured by a lambda. See 1.13.
Related¶
- 1.2 Records — the better choice for public return types
- 1.17 Pattern matching — tuple patterns in switch expressions
- 1.25
Span<T>— whereinandrefgenuinely matter - 22.13 The Result pattern — the alternative to tuples for success/failure