Codectionary / Developer documentation / C#

Span Views over Arrays

Span<T> is a stack-only view of contiguous memory. Slicing a span produces another view into the same data rather than copying elements. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

Span<T> is a stack-only view of contiguous memory. Slicing a span produces another view into the same data rather than copying elements. Use a .NET 8+ console project; replace Program.cs with this C# example.

The first element in middle is data[1]. Mutating the view therefore changes the original array.

Syntax

Span<T> view = array.AsSpan(start, length);

Examples

Span Views over Arrays

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
int[] data = { 10, 20, 30, 40 };
Span<int> middle = data.AsSpan(1, 2);
middle[0] = 99;
Console.WriteLine(string.Join(",", data));
Console.WriteLine(middle.Length);
  1. Expected output: 10,99,30,40 2
  2. The first element in middle is data[1]. Mutating the view therefore changes the original array.
  3. Use ReadOnlySpan<T> when consumers should not mutate the viewed memory.

Best practices

  • Use ReadOnlySpan<T> when consumers should not mutate the viewed memory.
  • Respect ref-struct lifetime restrictions; use Memory<T> when a view must be stored across asynchronous boundaries.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading