Span<T>
Learn safe memory views with Span<T>.
What is Span<T>?
Span<T> is a ref struct that provides a safe view over a region of memory. It wraps arrays, stack memory or native memory, checks bounds and offers low-cost access without unsafe.
Span<int> s = stackalloc int[4]; safely wraps stack memory. Span cannot be used in async methods because it must live on the stack; this restriction prevents misuse.
Span and arrays
To wrap an existing array in a Span, use Span<int> s = arr.AsSpan(); or Span<int> s = new Span<int>(arr);.
The indexer (s[0]) and the Slice method work on Span; Slice returns a sub-view without copying memory. This yields performance gains when processing parts of large arrays and keeps the code simple.
Exercise Sum values with Span
Declare Span<int> s = stackalloc int[3];. Assign s[0] = 4; s[1] = 5; s[2] = 6;. Compute int sum = s[0] + s[1] + s[2]; and print it with Console.WriteLine(sum);.
Show example solution
Span<int> s = stackalloc int[3]; s[0] = 4; s[1] = 5; s[2] = 6; int sum = s[0] + s[1] + s[2]; Console.WriteLine(sum);
Example solution:
using System;
class Program
{
static void Main()
{
Span<int> s = stackalloc int[3];
s[0] = 4;
s[1] = 5;
s[2] = 6;
int sum = s[0] + s[1] + s[2];
Console.WriteLine(sum);
}
}
Test yourself
-
What is the advantage of Span<T>?
- It can be used in async methods
- Automatic GC collection
- Bounds checking and low-cost access
- It modifies managed strings
Show answer
Bounds checking and low-cost access — Correct. Span checks bounds and is low-cost.
-
Match the Span members
- Span<T>
- Memory view
- AsSpan()
- Wrap an array
- Slice(i, n)
- Sub-view
- ref struct
- Must live on stack
-
Span with stackalloc
Span<int> s = ____ int[3];Show answer
Span<int> s = stackalloc int[3];