Span and Memory
Span and Memory
A span is a bounded view of contiguous elements, not a new array. Slicing adjusts the viewed region without copying the elements. Span<T> supports writes; ReadOnlySpan<T> restricts writes through that view, but another alias can still change its backing storage. Memory<T> and ReadOnlyMemory<T> are ordinary structs that can be stored in fields and carried across an await. A view is not an ownership contract: the owner must keep its buffer valid for the entire use.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Parse a field without creating a substring
The format is exactly two decimal digits after Q=. Check the prefix and length before indexing; choose an explicit culture for numeric parsing.
using System;using System.Globalization;ReadOnlySpan<char> input = "Q=42".AsSpan();if (input.Length == 4 && input[..2].SequenceEqual("Q=".AsSpan()) && input[2] is >= '0' and <= '9' && input[3] is >= '0' and <= '9' && int.TryParse(input[2..], NumberStyles.None, CultureInfo.InvariantCulture, out int quantity)) Console.WriteLine(quantity);else Console.WriteLine("invalid");The length check protects indexing. The range checks restrict the protocol to ASCII digits; TryParse consumes the remaining span directly with invariant culture.
Expected observation (reasoned, not executed):
42Observe aliasing and make an independent copy
An array-backed span aliases the array. ToArray creates a separate array containing the selected values.
using System;int[] stock = { 3, 5, 7 };Span<int> middle = stock.AsSpan(1, 1);ReadOnlySpan<int> readOnly = middle;int[] snapshot = middle.ToArray();middle[0] = 9;Console.WriteLine(stock[1]);Console.WriteLine(readOnly[0]);Console.WriteLine(snapshot[0]);Both views see the mutation. The snapshot keeps the old value because it copied an int. For reference elements, ToArray copies references, not the referenced objects.
Expected observation (reasoned, not executed):
995Retain a memory view across an await
Keep Memory<int> across the suspension, and obtain its span only for synchronous access. The caller owns an ordinary array for this entire operation.
using System;using System.Threading.Tasks;int[] data = { 10, 20, 30 };await UpdateAsync(data.AsMemory(1, 2));Console.WriteLine(string.Join(",", data));static async Task UpdateAsync(Memory<int> segment){ await Task.Yield(); segment.Span[0] += 5;}Task.Yield permits a continuation; no particular thread is guaranteed. Memory survives the suspension but does not itself make access thread-safe. Await completion before reusing or returning a borrowed buffer.
Expected observation (reasoned, not executed):
10,25,30Common mistakes and design trade-offs
A span is not necessarily backed by stack memory. Read-only views are not immutable snapshots. A span slice is normally allocation-free, but the full program may allocate. Do not retain a borrowed memory segment beyond its lease. Do not infer speed without measurements.
Apply the concept
Design a parser for a fixed field N=07 that rejects missing prefixes and incorrect lengths. Explain when to keep a ReadOnlySpan<char>, when to copy, and what changes if the caller returns a pooled buffer.
Check your work: The expected numeric value is 7. A synchronous parser can use a read-only span; copying is appropriate when independent storage is needed. A memory view cannot outlive a returned pool lease even if the type can be stored.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Span and Memory — knowledge check
Apply the lesson concepts to the following scenarios.
What does slicing a span normally copy?
After a writer changes an array element, what may a read-only span over it observe?
Which can be retained across an await?
When is a copy useful?
What does a Memory<T> value guarantee about a pool lease?