In C#, what does the compiler generate for await using, and why does a plain using on an IAsyncDisposable-only type fail with CS8418?
answer
- same shape as using
- finally with a null check
- last declared, first disposed
- keyword picks the interface
basics
~20 sawait using compiles to try/finally that, if the resource is not null, awaits DisposeAsync in the finally; declarations dispose in reverse order. A plain using only accepts IDisposable, so an IAsyncDisposable-only type gets CS8418, suggesting await using.
solid answer
~40 s`await using` is lowered like `using`, but with `IAsyncDisposable` and an awaited `DisposeAsync()`: the resource is stored in a local, the body goes in `try`, and the `finally` awaits `DisposeAsync()` if the local is not `null`. Several declarations nest, so the last one declared is disposed first. The binder first looks for a pattern-based `DisposeAsync()` (an accessible instance method, never an extension), then for the interface. A plain `using` only accepts `IDisposable`, so a type with only `IAsyncDisposable` fails with CS8418, "Did you mean 'await using' rather than 'using'?"; the reverse mismatch is CS8417. On a type with both interfaces, `using` calls only `Dispose` and `await using` only `DisposeAsync`.
code
csharp · 20 linesawait RunAsync();
static async Task RunAsync()
{
await using var first = new Publisher("first");
await using var second = new Publisher("second");
await using Publisher? none = null; // null: no DisposeAsync call, no exception
using var sync = new Publisher("sync"); // plain using on a type with both: Dispose
Console.WriteLine("end of block");
}
sealed class Publisher(string name) : IDisposable, IAsyncDisposable
{
public void Dispose() => Console.WriteLine($"{name}: Dispose");
public async ValueTask DisposeAsync()
{
await Task.Yield();
Console.WriteLine($"{name}: DisposeAsync");
}
}go deeper
Know that await using is the asynchronous form of using and that it awaits DisposeAsync at the end of the scope, even when an exception is thrown.
Explain the try/finally expansion with its null check, reverse disposal order for declarations, and the CS8418 and CS8417 pair that rejects a keyword that does not match the interface.
Show you know the keyword, not the type, decides which method runs on a dual-interface type, and that pattern-based DisposeAsync works without the interface but never through an extension method.
Connect the compile-time strictness to API design: because the compiler will not bridge sync and async cleanup, a type's interface set dictates which call sites can release it at all.
## Two forms, one expansion C# 8 added **`await using`** in the same two shapes as `using`: - the **statement**: `await using (var p = new Publisher()) { ... }`, scoped to its block; - the **declaration**: `await using var p = new Publisher();`, scoped to the end of the block that contains it. Both are lowered the same way as a plain `using`, with `IAsyncDisposable` in place of `IDisposable` and an awaited `DisposeAsync()` in place of `Dispose()`. Roslyn's using-statement rewriter describes the expansion as roughly: ```csharp Publisher p = new Publisher(); try { // body } finally { if (p != null) await ((IAsyncDisposable)p).DisposeAsync(); } ``` Three consequences follow from that shape: 1. **A null resource is fine.** The `finally` checks for `null`, so `await using Publisher? p = null;` neither calls anything nor throws. 2. **Cleanup runs on every exit path**: normal completion, `return`, `break` or an exception. 3. **Several declarations dispose in reverse order.** Each declaration opens its own nested `try`/`finally`, so the last one declared is disposed first. For a value-type resource the compiler emits a constrained call that avoids boxing where it can. ## How the compiler finds DisposeAsync For `await using`, the binder first looks for a **pattern-based** `DisposeAsync()` method: an accessible instance method callable without arguments whose result can be awaited. A class with a public `ValueTask DisposeAsync()` works even without implementing the interface. If no such method is found, it falls back to the `IAsyncDisposable` interface. Extension methods are never considered: a `DisposeAsync` extension method on a plain class still yields **CS8410**. ## Matching the keyword to the interface The compiler rejects a mismatch and says what you probably meant. These are the SDK's messages without the leading type name (CS4033: its first sentence): | Code | Situation | Message | |---|---|---| | **CS8418** | `using` on a type that implements only `IAsyncDisposable` | type used in a using statement must implement 'System.IDisposable'. Did you mean 'await using' rather than 'using'? | | **CS8417** | `await using` on a type that implements only `IDisposable` | type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. Did you mean 'using' rather than 'await using'? | | **CS8410** | `await using` on a type with neither | type used in an asynchronous using statement must implement 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. | | **CS4033** | `await using` inside a non-async method | The 'await' operator can only be used within an async method. | A plain `using` never falls back to `DisposeAsync`, and `await using` never falls back to `Dispose`. That is the point of CS8418: there is no synchronous way to call an asynchronous cleanup without blocking, so the compiler refuses rather than guessing. ## A type that implements both interfaces When a type implements both, **the keyword decides**: - `using` calls `Dispose()` only; - `await using` awaits `DisposeAsync()` only. They are never both called by the compiler. That is why the two methods must do equivalent work; the type itself, not the language, keeps them consistent. ## What the variable allows A variable declared by either form is **read-only**: you cannot reassign it or pass it by `ref` or `out`, and the `finally` disposes the value it was initialized with. A using declaration, awaited or not, also cannot sit directly in a `switch` section without braces (**CS8647**). ## Mistakes the expansion explains - **"It throws on null."** It does not; the `finally` tests the resource first. - **"Dispose and DisposeAsync both run."** Only the one matching the keyword runs, so a type whose `Dispose` and `DisposeAsync` do different work behaves differently depending on which keyword the caller typed. - **"Declarations dispose top to bottom."** They dispose bottom to top, which is usually what you want: a writer declared after the stream it wraps is flushed and closed before that stream. - **"An extension method can add async disposal to a type I do not own."** Pattern lookup ignores extension methods; wrap the type in your own class instead. - **"The `using` variable can be swapped mid-scope."** It is read-only, so the object disposed is always the one created on that line.
- Does await using need the type to implement IAsyncDisposable?No. The compiler first looks for a pattern-based `DisposeAsync()`: an accessible instance method callable without arguments whose result is awaitable. A class with a public `ValueTask DisposeAsync()` works without the interface. Extension methods are not considered, so adding a `DisposeAsync` extension to a plain class still fails with CS8410.
- Why does the compiler refuse instead of calling DisposeAsync synchronously for a plain using?Running asynchronous cleanup from a synchronous `finally` would mean blocking on the returned `ValueTask`, which ties up a thread and can deadlock on a single-threaded synchronization context. The language makes that choice visible: write `await using` in async code, or have the type implement `IDisposable` with a real synchronous path.
- A plain using calls DisposeAsync if the type has no Dispose method
- await using on a type with both interfaces calls Dispose and then DisposeAsync
- await using throws NullReferenceException when the resource is null
- Multiple await using declarations are disposed in declaration order
- An extension method named DisposeAsync makes any type usable with await using