Why does C# reject reader.ReadInto(scratch) with CS8350 when reader is a ref PacketReader and scratch is stackalloc memory, and how does scoped fix it?
answer
- every span value has a lifetime
- the method might store the argument
- the receiver outlives the buffer
- a promise not to capture
- scoped on the parameter
basics
~20 sThe compiler assumes ReadInto might store its Span<byte> argument in the reader, which outlives the stackalloc buffer, so the call could leak stack memory (CS8350, CS8352). Declaring the parameter scoped Span<byte> promises it never escapes, and the call compiles.
solid answer
~50 sEach ref struct value carries a **safe context**, how far it may escape: `scratch`, from `stackalloc`, may not leave the current method, while `reader`, a `ref` parameter wrapping heap bytes, may escape to the caller. `ReadInto(Span<byte> destination)` receives the reader by reference as `this`, and nothing in its signature stops it from writing `_buffer = destination;`. So the compiler's argument-matching rule rejects this call, which mixes a narrow argument with a wider ref struct receiver, reporting CS8350 on the call and CS8352 on `scratch`. `scoped` (C# 11) changes the parameter's contract: the method may read and write the span's elements but may not store or return the span, and trying to do so inside it is CS8352. The call then compiles. The same error appears with a local reader built over an array; it disappears if the reader also wraps stack memory, because then neither value outlives the other.
code
csharp · 31 linesusing System;
using System.Text;
var reader = new PacketReader(new byte[] { 3, 65, 66, 67, 2, 72, 73 });
Console.WriteLine(ReadLabel(ref reader));
Console.WriteLine(ReadLabel(ref reader));
static string ReadLabel(ref PacketReader reader)
{
Span<byte> scratch = stackalloc byte[64];
int n = reader.ReadInto(scratch); // CS8350 without 'scoped' below
return Encoding.ASCII.GetString(scratch[..n]);
}
ref struct PacketReader
{
private ReadOnlySpan<byte> _buffer;
private int _pos;
public PacketReader(ReadOnlySpan<byte> buffer) => _buffer = buffer;
public byte ReadByte() => _buffer[_pos++];
// 'scoped' promises the method never stores or returns 'destination'.
public int ReadInto(scoped Span<byte> destination)
{
int len = ReadByte();
_buffer.Slice(_pos, len).CopyTo(destination);
_pos += len;
// _buffer = destination; // now an error inside the method
return len;
}
}go deeper
Recall that the compiler tracks how far each span may escape, and that a span over stack memory may not leave its method.
Explain that the compiler checks calls from signatures alone, so an unscoped span parameter is assumed to be storable in the receiver.
Diagnose CS8350 and CS8352 from the two safe contexts involved and fix the API with scoped rather than by moving buffers to the heap.
Treat scoped as part of a published signature: adding it widens what callers can pass, while removing it later breaks their code.
## Two lifetimes the compiler tracks C#'s **ref safety** analysis gives every expression two lifetimes, both measured in scopes rather than time: - **ref-safe context**: how far a *reference to a variable* may escape (what CS8168 checks for `return ref`). - **safe context**: how far a *ref struct value* such as a `Span<T>`, may escape, which is set by the memory it points at. The contexts nest from widest to narrowest: **caller context** (may be returned to the caller), **function member** (may live anywhere in this method but not leave it), and the **declaration block** of a local. A span over a heap array has caller context. A span over `stackalloc` memory has function-member context, because the memory is freed when the method returns. ## Why the call is rejected ```csharp static string ReadLabel(ref PacketReader reader) { Span<byte> scratch = stackalloc byte[64]; int n = reader.ReadInto(scratch); // CS8350 + CS8352 return Encoding.ASCII.GetString(scratch[..n]); } ``` | Argument | Safe context | Why | |---|---|---| | `reader` (the receiver, passed by `ref`) | caller context | it wraps bytes the caller owns and is the caller's variable | | `scratch` | function member | it points at this method's stack memory | `ReadInto` is an instance method of a ref struct, so `reader` reaches it by reference and the method can assign to its fields. The compiler checks calls **without looking inside the callee**: it only sees the signature, so it must assume `ReadInto` could run `_buffer = destination;`. That would leave the caller's reader pointing at freed stack memory. The **method arguments must match** rule therefore requires that no argument with a narrower safe context be passed alongside a ref struct passed by `ref` (including the receiver) whose context is wider. The SDK reports CS8350 ("This combination of arguments to 'PacketReader.ReadInto(Span<byte>)' is disallowed because it may expose variables referenced by parameter 'destination' outside of their declaration scope") and CS8352 on `scratch`. ## What `scoped` promises `public int ReadInto(scoped Span<byte> destination)` narrows the parameter's own safe context to the method: - The method may read, write, slice and pass on `destination`, for example to `CopyTo` or `Encoding.ASCII.GetString`. - It may **not** store it in a field, assign it to a wider variable, or return it; `_buffer = destination;` becomes CS8352 inside the method. - Because the argument can no longer escape through the call, the caller's mix of lifetimes is safe and CS8350 disappears. - `scoped` costs nothing at run time; it is purely a compile-time contract. `scoped` arrived with C# 11 together with ref fields; at LangVersion 10 the SDK reports it as the feature 'ref fields' (CS8936). Overloads may not differ only by `scoped`, and an override must keep the base signature's `scoped` annotations except for the narrow cases the specification allows. ## `scoped` on locals A local takes its safe context from its initializer, so `Span<int> b = new int[2];` has caller context and `b = a;` with `a` from `stackalloc` is CS8352. Declaring `scoped Span<int> b = new int[2];` limits `b` to the method, after which the assignment compiles. Copying or slicing the narrow span does not help, because the copy keeps the same safe context. ## Other ways out 1. **Add `scoped`** to the parameter when the method genuinely never keeps the span; this is the normal fix and documents the contract. 2. **Match the lifetimes**: a reader built over stack memory and a stack buffer have the same context, so the call compiles without `scoped`. 3. **Return data, not views**: have the reader copy into a caller-owned array, or return a count and let the caller slice its own buffer. ## Reading the related diagnostics | Diagnostic | Meaning | |---|---| | CS8352 | a variable is used where its referenced memory could escape | | CS8350 | a call's argument combination could store a narrow argument in a wider one | | CS8347 | a call's *result* could carry a narrow argument out of scope | All three are ref-safety errors decided at compile time; none corresponds to a run-time check.
- Why does the same call compile when the reader itself wraps stackalloc memory?The argument-matching rule only objects when a narrower argument could be stored into a wider ref struct. A reader created over a `stackalloc` buffer in the same method has the same function-member context as `scratch`, so even if `ReadInto` stored the span, nothing could outlive the memory it points at. The call compiles without `scoped`.
- What is [UnscopedRef] and how does it relate to scoped?It is the opposite annotation, in System.Diagnostics.CodeAnalysis since C# 11: it widens a reference's ref-safe context by one level. Typical uses are a struct property returning a ref to its own field, which is CS8170 by default, and an `out` parameter, which C# 11 treats as scoped by default. Use it sparingly, because it widens what callers must keep alive.
- Can a method overload differ only by scoped on a parameter?No. The C# 11 design states that overloads cannot differ only on `scoped` or `[UnscopedRef]`, and an override, interface implementation or delegate conversion must match them except for a few listed relaxations, such as removing `[UnscopedRef]` from an `out` parameter. Treat `scoped` as part of the public signature: adding it later is safe for callers, removing it breaks them.
- CS8350 means the stackalloc buffer is too large for the stack.
- Copying scratch into another Span<byte> local avoids the error.
- scoped makes the compiler move the buffer to the heap.
- scoped is checked at run time and throws if the span escapes.
- Passing the reader by value instead of by ref always removes CS8350.