Understanding the Span<T> data type in C#
Posted: (EET/GMT+2)
If you've been working with arrays, strings, and buffers in .NET for years, the new Span<T> type may look like just another wrapper. But it represents a significant step forward in how we can safely and efficiently work with memory.
A Span<T> is a stack-only type that provides a "window" into contiguous memory, whether that memory comes from an array, a portion of a string, unmanaged memory, or even the stack itself.
You can think of it as a slice view without creating a copy:
Int[] numbers = new int[] { 1, 2, 3, 4, 5 };
Span middle = numbers.AsSpan(1, 3); // {2,3,4}
middle[0] = 99; // changes numbers[1] too
Because Span<T> lives on the stack, it avoids the overhead of heap allocations and the GC (garbage collector). This makes it ideal for tight loops, parsing, and data transformation operations.
For read-only views, there is even a ReadOnlySpan<T>, and for strings, you'll often see ReadOnlySpan<char> used in newer APIs.
The .NET team built much of the System.Memory namespace around these ideas, and the runtime already uses spans internally in several performance-critical areas. It's one of those additions that quietly modernizes the entire framework and brings more performance.
Expect to see more of Span<T> showing up in multiple places in the coming .NET releases.