Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Span and Memory: buffer views without copying

Span<T> and Memory<T> describe regions of existing buffers without copying their elements. Learn their lifetime restrictions, read-only variants, and text processing with AsSpan, IndexOf, SequenceEqual, and TryParse.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Span<T>; ReadOnlySpan<T>; Memory<T>; ReadOnlyMemory<T>; text.AsSpan(); span[start..end]; memory.Span; "text"u8

Span<T> is a writable view over contiguous memory, while ReadOnlySpan<T> permits only reading through the view. Creating or slicing a view does not copy elements. A span itself is a ref struct; its data can reside, for example, in a heap array or stack memory. ReadOnly restricts access through the view but does not guarantee that another access path cannot modify the buffer.

Memory<T> and ReadOnlyMemory<T> can be stored in class fields and retained across await; their .Span property exposes a view for synchronous processing. They do not own the buffer: do not use a view after its buffer is returned to a pool or its permitted usage period ends. A span cannot be captured in a lambda or stored in a class field. Since C# 13, local spans are permitted in async methods with restrictions; they cannot survive an await. Before C# 13, they were prohibited in these methods.

MemoryExtensions.AsSpan creates a view; for a string, it returns a ReadOnlySpan<char> of UTF-16 code units. MemoryExtensions.IndexOf returns the first zero-based index or -1: check the result before slicing. MemoryExtensions.SequenceEqual compares lengths and corresponding elements, not view identity; for char, it does not perform culture-sensitive linguistic comparison.

Int32.TryParse(ReadOnlySpan<char>, ...) and Decimal.TryParse(ReadOnlySpan<char>, ...) parse a slice without creating a substring. Check the returned bool; specify NumberStyles and CultureInfo.InvariantCulture for a predictable format. Both methods return false for invalid numeric text, but invalid style arguments can throw exceptions. Int32.TryParse also returns false for values outside the Int32 range. In contrast, Decimal.TryParse can round a value slightly above decimal.MaxValue down to decimal.MaxValue and return true. For example, this happens with 79228162514264337593543950335.1 when using NumberStyles.Number and CultureInfo.InvariantCulture.

A UTF-8 string literal with the u8 suffix, such as "OK"u8, is available since C# 11 and produces ReadOnlySpan<byte>, not string or ReadOnlySpan<char>. Its length counts bytes, not characters. The example targets net10.0 with LangVersion=preview but uses established features rather than features requiring preview mode.

Reference identifiers covered by this entry: UTF-8 string literal u8.

Examples

using System;
using System.Globalization;

ReadOnlyMemory<char> memory = "42;12.50".AsMemory();
ReadOnlySpan<char> text = memory.Span;
int separator = text.IndexOf(';');
if (separator < 0)
    throw new FormatException("Missing separator.");

bool countOk = int.TryParse(text[..separator], NumberStyles.Integer,
    CultureInfo.InvariantCulture, out int count);
bool priceOk = decimal.TryParse(text[(separator + 1)..], NumberStyles.Number,
    CultureInfo.InvariantCulture, out decimal price);
if (!countOk || !priceOk)
    throw new FormatException("Invalid number.");

Console.WriteLine(text[..separator].SequenceEqual("42".AsSpan()));
Console.WriteLine((count * price).ToString("F2", CultureInfo.InvariantCulture));
ReadOnlySpan<byte> command = "OK"u8;
Console.WriteLine(command.SequenceEqual("OK"u8));

Result

True
525.00
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources