Phase 19 of 30 · Topic 19.1

`Span<T>` & `ReadOnlySpan<T>`: Contiguous Memory Windows

1Concept

`Span<T>` is a `ref struct` representing a contiguous region of arbitrary memory (stack, native heap, or managed array). Slicing a span (`span.Slice(start, length)`) creates a view with zero memory allocations.

2Architecture Diagram

Original Managed Array: [ '2', '0', '2', '6', '-', '0', '8', '-', '2', '9' ]
                                     │
         span.Slice(0, 4) ───────────┴───────────> [ '2', '0', '2', '6' ] (Zero Allocations!)
         span.Slice(5, 2) ───────────────────────> [ '0', '8' ] (Zero Allocations!)

3Code Example

C# 13 & .NET 9
using System;

public class SpanSlicingDemo
{
    public static void Main()
    {
        ReadOnlySpan<char> dateSpan = "2026-08-29".AsSpan();

        // Zero-allocation string parsing
        ReadOnlySpan<char> yearSpan = dateSpan.Slice(0, 4);
        ReadOnlySpan<char> monthSpan = dateSpan.Slice(5, 2);
        ReadOnlySpan<char> daySpan = dateSpan.Slice(8, 2);

        int year = int.Parse(yearSpan);
        int month = int.Parse(monthSpan);
        int day = int.Parse(daySpan);

        Console.WriteLine($"Parsed Date without string.Substring() allocations: Year={year}, Month={month}, Day={day}");
    }
}

4Expected Output

Parsed Date without string.Substring() allocations: Year=2026, Month=8, Day=29

5Key Takeaways

  • `Span<T>` slices memory in O(1) time without allocating sub-strings or arrays.
  • Being a `ref struct`, `Span<T>` can only live on the stack and cannot be boxed or placed in classes.
  • Use `ReadOnlySpan<char>` instead of `string` for high-throughput string parsing.