skip to content

Why does C# reject async Task<bool> TryLoadAsync(string path, out string text) with CS1988, and how do you return both results instead?

level: middleimportance: should knowfreq 45%

answer

  1. the method returns before it finishes
  2. state machine kept on the heap
  3. same rule for iterators
  4. return a tuple or a result

basics

~20 s

An async method hands its Task back at the first pending await and finishes later, so it cannot keep a reference to the caller's variable. Return Task<(bool Ok, string Text)>, a result record or a nullable value instead.

solid answer

~50 s

The compiler rewrites an `async` method into a state machine. At the first `await` that does not complete at once, the method returns a `Task` to its caller and keeps its locals and parameters in an object on the heap until it resumes. A `ref`, `out`, `in` or `ref readonly` parameter is a reference to a caller's variable, possibly a local in a stack frame that is already gone, and such a reference cannot be stored in a heap object, so CS1988 rejects the declaration. Iterators fail the same way with CS1623, because their body runs later, on `MoveNext`. Return the pair instead: `Task<(bool Ok, string Text)>`, a small result record, or `Task<string?>` with null for failure. C# 13 allowed `ref` locals and `Span<T>` locals in these methods when no `await` or `yield` falls inside their lifetime; by-reference parameters are still rejected.

code

csharp · 22 lines
csharp
int[] buffer = [1, 2, 3];
Console.WriteLine(await Loader.SumThenWaitAsync(buffer));
var (ok, text) = await Loader.TryLoadAsync("missing.txt");
Console.WriteLine($"{ok} '{text}'");

static class Loader
{
    public static async Task<int> SumThenWaitAsync(int[] data)
    {
        await Task.Yield();
        ref int first = ref data[0];   // C# 13: a ref local is allowed in an async method...
        first += 100;                  // ...as long as no await runs while it is in scope
        await Task.Delay(1);
        return data[0];
    }

    public static async Task<(bool Ok, string Text)> TryLoadAsync(string path)
    {
        if (!File.Exists(path)) return (false, "");
        return (true, await File.ReadAllTextAsync(path));
    }
}

go deeper

for a junior

Recall that async methods and iterators cannot declare ref, out or in parameters, and that the usual replacement is returning a tuple or a result object.

for a middle

Explain the mechanism: the method returns its Task at the first pending await and resumes later from a heap-held state machine, where a reference to a caller's variable cannot live.

for a senior

Design async Try APIs well: choose between a tuple, a result record and a nullable result, and know what C# 13 relaxed for ref and Span<T> locals and what it did not.

for a principal

Set the team's convention for asynchronous operations that can fail expectedly, so results stay consistent across services instead of mixing tuples, nulls and exceptions.

## The rule and its two diagnostics C# forbids by-reference parameters in two kinds of methods, and the compiler reports it on the parameter declaration itself, whatever the body does: - **CS1988**, *Async methods cannot have ref, in or out parameters*, for any method marked `async`. The SDK 10.0.401 compiler reports the same error for `ref readonly` parameters, although the message names only three modifiers. - **CS1623**, *Iterators cannot have ref, in or out parameters*, for any method whose body contains `yield return` or `yield break`. So `async Task<bool> TryLoadAsync(string path, out string text)` never compiles, whatever its body does. ## Why a reference cannot survive a suspension A by-reference parameter is an alias for a variable the caller owns, often a local in the caller's stack frame. An `async` method breaks the assumption that the callee finishes before the caller continues. The sequence the compiler has to support is: 1. The caller runs `TryLoadAsync(path, out text)`, with `text` a local in its own frame. 2. The method runs synchronously until it reaches an `await` on a task that has not completed yet. 3. At that point it returns a `Task<bool>` to the caller and stores its state, locals and parameters included, in a state machine object that lives on the heap. 4. The caller carries on. It may await the task, or it may return, taking its stack frame and the `text` local with it. 5. When the awaited work completes, the method resumes, possibly on another thread, and would now have to write `text`. The runtime only allows a managed reference (`ref`) to live on the stack or inside a `ref struct`; it cannot be stored in a field of a heap object, because nothing would keep the variable it points at alive. A by-value parameter has no such problem: it is copied into the state machine like any other local. There is also a problem of time. An `out` parameter is supposed to be assigned when the call returns, but an async method returns at step 3, before the value exists. ## Iterators: the same problem, lazily An iterator such as `IEnumerable<int> Range(int start, ref int produced)` is also rewritten into a state machine object. Calling it runs none of the body; the body runs piece by piece on each `MoveNext`, which may happen long after the call returned, or never. A reference captured at the call would have to outlive the caller's frame in exactly the same way, so CS1623 rejects it. ## Returning several results from async code | Option | Signature | When it fits | |---|---|---| | Value tuple | `Task<(bool Ok, string Text)>` | private and internal helpers; names travel with the tuple | | Result record | `Task<LoadResult>` | public APIs; named type that can grow new members | | Nullable result | `Task<string?>` | when absence is the only failure; nullable annotations guide callers | | Exception | `Task<string>` that throws | when failure is genuinely exceptional, not an expected outcome | A caller of the tuple form writes `var (ok, text) = await TryLoadAsync(path);`; how that deconstruction works belongs to the lesson on tuples. A synchronous `bool TryParse(string s, out T value)` stays the right shape for in-memory work: the restriction is about `async` and iterators, not about `out` in general. ## What C# 13 relaxed, and what it did not C# 13 (.NET 9) lifted a related restriction. Inside `async` methods and iterators you may now declare `ref` locals, locals of `ref struct` types such as `Span<T>`, and `unsafe` blocks, provided no `await` or `yield` occurs while they are in scope: - A `ref int first = ref data[0];` used between two awaits compiles; under `LangVersion` 12 the same code reports CS9202, a feature not available in C# 12. - Keeping that `ref` local alive across an `await` is still an error, CS9217, *A 'ref' local cannot be preserved across 'await' or 'yield' boundary*. - By-reference **parameters** were not part of the change: CS1988 and CS1623 still apply in C# 13 and C# 14. The rule behind both is the same: a reference may exist only while the method is running on the caller's stack, never while it is suspended.

  • What exactly did C# 13 change about ref inside async methods and iterators?
    It allows `ref` locals, `ref struct` locals such as `Span<T>`, and `unsafe` blocks in async methods and iterators, as long as no `await` or `yield` occurs while they are in scope; crossing one is CS9217. With `LangVersion` 12 the same code reports CS9202. By-reference parameters are still rejected with CS1988 and CS1623.
  • Why can't the compiler copy the out value back to the caller when the Task completes?
    Because by then the caller may have moved on: it received the Task at the first pending await and could already have returned, discarding the local the reference pointed to. C# by-reference parameters are live aliases with no copy-back step, and a Task's completion has no way to write into a caller's stack frame.
  • How should a public API expose an asynchronous Try operation?
    Return a type that carries both outcomes: a named result record, a tuple such as `Task<(bool Found, Order Value)>` for internal code, or `Task<Order?>` when absence is the only failure. Name the members so callers can deconstruct or pattern-match the result, and keep a synchronous `bool TryX(out T)` overload only for work that never awaits.

  • C# 13 lifted the ban on ref and out parameters in async methods.
  • in parameters are fine in async methods because they are read-only.
  • The compiler copies an async method's out value back when the Task completes.
  • Iterators may take ref parameters because their body runs synchronously.
  • CS1988 only appears when the out parameter is assigned after an await.

Assumes C# 14; C# 13 began allowing ref locals and ref struct locals in async methods and iterators between awaits and yields, while by-reference parameters stay forbidden.