C# Interview Question #118

What is Span<T> in C#?

Concurrency, Performance & Design Senior Advanced

Quick Interview Answer

Span<T> is a stack-only type representing a contiguous region of memory. It can provide efficient slicing and processing of arrays, stack memory, strings through related read-only spans, and other buffers without allocating new objects for many operations.

Detailed Explanation

Span<T> is a stack-only type representing a contiguous region of memory. It can provide efficient slicing and processing of arrays, stack memory, strings through related read-only spans, and other buffers without allocating new objects for many operations.

ReadOnlySpan<T> provides read-only access. Because Span<T> is a ref struct, it has restrictions: it cannot normally be stored in heap objects or used across await boundaries.

Span is mainly important in high-performance libraries, parsing, protocol handling, and allocation-sensitive code. Normal business application code should use it only when measurement shows a benefit or an API naturally exposes it.

Code Example

int[] numbers = { 10, 20, 30, 40, 50 };

Span<int> span = numbers.AsSpan(1, 3);

foreach (int number in span)
{
    Console.WriteLine(number);
}