Skip to main content

How to Read a ReadOnlyMemory<T> Through Its Span in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

A ReadOnlyMemory<int> holds a block of numbers, but you can't index it or loop over it. Its Span property gives you a ReadOnlySpan<int> over the same numbers, which you can index and loop over.

Microsoft's reference describes ReadOnlyMemory<T> like this: Represents a contiguous region of memory, similar to ReadOnlySpan<T>. Unlike ReadOnlySpan<T>, it is not a byref-like type. In plain words, it's a read-only view of a block of items, such as an array. Its Span property: Gets a span from the memory region.

You usually meet one when an API returns it. To read its items, you take its span.

Syntax​

Syntax
ReadOnlySpan<T> <span> = <memory>.Span;
T <item> = <span>[<index>];
PartWhat it is
TThe type of the items, such as int or float
<memory>A ReadOnlyMemory<T>, such as one an API returned
.SpanThe property that returns a ReadOnlySpan<T> over the same items
<span>[<index>]One item, by its position. Positions start at 0

The span's indexer, in the reference's words: Gets an item from the read-only span at the specified zero-based index. A foreach loop over the span reads every item, and Length counts them.

The Example​

A console app called MemorySpan keeps a week of step counts in a ReadOnlyMemory<int>, then reads them through its Span: the number of days, the first and last day, and the week's total.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n MemorySpan
cd MemorySpan
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/MemorySpan/MemorySpan.csproj:
Determining projects to restore...
Restored /Users/you/source/MemorySpan/MemorySpan.csproj (in 37 ms).
Restore succeeded.

dotnet new console -n MemorySpan creates a folder named MemorySpan with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or MemorySpan.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the memory:

Program.cs (the memory)
// A week of step counts. An array converts to ReadOnlyMemory<int> by itself.
int[] counts = [4200, 6100, 3900, 8000, 7200, 10500, 5600];
ReadOnlyMemory<int> week = counts;
Console.WriteLine($"Days in the memory: {week.Length}");
  • [4200, 6100, ...] is an array of seven whole numbers.
  • ReadOnlyMemory<int> week = counts; works without any conversion code. The reference: Defines an implicit conversion of an array to a ReadOnlyMemory<T>.
  • week.Length comes from the memory itself, which knows its size: Gets the number of items in the memory region.

Then the span:

Program.cs (the span)
// To read the items, take the memory's Span.
ReadOnlySpan<int> steps = week.Span;
Console.WriteLine($"First day: {steps[0]}");
Console.WriteLine($"Last day: {steps[steps.Length - 1]}");

int total = 0;
foreach (int step in steps)
{
total += step;
}
Console.WriteLine($"Week total: {total}");
  • week.Span returns a ReadOnlySpan<int> over the same seven numbers.
  • steps[0] is the first item, and steps[steps.Length - 1] the last, because positions start at 0.
  • foreach reads the items one by one, and total += step adds each one to the total.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Days in the memory: 7
First day: 4200
Last day: 5600
Week total: 45500

macOS-style terminal window titled Terminal — MemorySpan showing dotnet run printing Days in the memory: 7, First day: 4200, Last day: 5600 and Week total: 45500

  • week.Length gave 7, straight from the memory.
  • Through the span, steps[0] read 4200 and steps[steps.Length - 1] read 5600.
  • The foreach loop added all seven days up to 45500.

The Complete File​

macOS-style code window titled Program.cs — MemorySpan showing an array of seven step counts assigned to a ReadOnlyMemory of int, its Length, its Span stored in a ReadOnlySpan of int, the first and last items read by position, and a foreach loop that adds up the week's total

Program.cs
// A week of step counts. An array converts to ReadOnlyMemory<int> by itself.
int[] counts = [4200, 6100, 3900, 8000, 7200, 10500, 5600];
ReadOnlyMemory<int> week = counts;
Console.WriteLine($"Days in the memory: {week.Length}");

// To read the items, take the memory's Span.
ReadOnlySpan<int> steps = week.Span;
Console.WriteLine($"First day: {steps[0]}");
Console.WriteLine($"Last day: {steps[steps.Length - 1]}");

int total = 0;
foreach (int step in steps)
{
total += step;
}
Console.WriteLine($"Week total: {total}");

Common Mistakes​

MistakeWhat happensDo this instead
Reading an item from the memory itself, as in week[0]error CS0021: Cannot apply indexing with [] to an expression of type 'ReadOnlyMemory<int>'Read it through the span, as the example does with steps[0]
Looping over the memory with foreach (int step in week)error CS1579: foreach statement cannot operate on variables of type 'ReadOnlyMemory<int>' because 'ReadOnlyMemory<int>' does not contain a public instance or extension definition for 'GetEnumerator'Loop over its span: foreach (int step in week.Span)
Changing an item through the span: week.Span[0] = 5000;error CS8331: Cannot assign to property 'this' or use it as the right hand side of a ref assignment because it is a readonly variableWhen the code must change items, use Memory<int>, whose span is writable: the same line then changed counts[0] to 5000

FAQ​

Does the span copy the items?​

No. It reads the items the memory points to. After counts[0] = 9999;, a span taken before the change printed 9999 for steps[0]. Microsoft's guidelines: Span<T> and ReadOnlySpan<T> are lightweight memory buffers that wrap references to managed or unmanaged memory.

Why do APIs return a ReadOnlyMemory<T> and not a span?​

A span can't go everywhere. The guidelines: Because these types can only be stored on the stack, they're unsuitable for scenarios such as asynchronous method calls. And: Unlike Span<T>, Memory<T> can be stored on the managed heap. Two checks showed it:

  • A class field of type ReadOnlySpan<int> didn't build: error CS8345: Field or auto-implemented property cannot be of type 'ReadOnlySpan<int>' unless it is an instance member of a ref struct. As a ReadOnlyMemory<int> field, it built, and log.Steps.Span[0] printed 4200.
  • An async method with a ReadOnlySpan<int> parameter didn't build: error CS4012: Parameters of type 'ReadOnlySpan<int>' cannot be declared in async methods or async lambda expressions. With a ReadOnlyMemory<int> parameter, read through .Span, it returned 14200.

Conclusion​

To read a ReadOnlyMemory<T>, take its Span, then index it, loop over it with foreach and count it with Length. Keep the memory where a span can't go, such as in a field or across an await, and take the span at the point where you read the items.

Additional Resources​