skip to content

In C#, what is a Span<T>, what memory can it point at, and why does slicing one not copy anything?

level: juniorimportance: must knowfreq 72%

answer

  1. a window, not a container
  2. pointer plus length
  3. array, string, stack, native
  4. writes reach the original
  5. ToArray and ToString copy

basics

~20 s

Span<T> is a view over existing contiguous memory, such as an array, a string's characters, stackalloc memory or native memory. It holds only a reference and a length, so Slice returns another view of the same memory, not a copy.

solid answer

~40 s

`Span<T>` is a small struct that holds a reference to the first element and a length; it owns nothing. It can sit over an array (`array.AsSpan()`), over stack memory (`Span<byte> buf = stackalloc byte[16]`) or over native memory through the unsafe pointer constructor, and `string.AsSpan()` gives a `ReadOnlySpan<char>` over a string's characters. `Slice(start, length)` or a range such as `span[1..4]` only moves the reference and shortens the length, so no elements are copied, and a bad bound throws `ArgumentOutOfRangeException`. Because it is a view, writing `span[0] = 999` changes the underlying array. A copy happens only when you ask for one: `ToArray()`, `ToString()` or `CopyTo`. Span is a `ref struct`, so it lives on the stack and cannot be stored in a class field.

code

csharp · 20 lines
csharp
int[] latencies = [120, 85, 230, 40, 310, 95];

Span<int> lastThree = latencies.AsSpan(3);       // view, no copy
lastThree[0] = 999;                              // writes through to the array
Console.WriteLine(string.Join(",", latencies));  // 120,85,230,999,310,95

ReadOnlySpan<int> middle = latencies.AsSpan()[1..4];
Console.WriteLine($"{middle.Length} {middle[0]}");  // 3 85

string line = "GET /api/orders 200";
ReadOnlySpan<char> verb = line.AsSpan(0, 3);     // no substring allocated
Console.WriteLine(verb.ToString());              // GET (ToString copies)

Span<byte> scratch = stackalloc byte[16];        // stack memory, no heap
scratch.Fill(0xFF);
Console.WriteLine(scratch[15]);                  // 255

int[] copy = lastThree.ToArray();                // explicit copy
copy[0] = 1;
Console.WriteLine(latencies[3]);                 // still 999

go deeper

for a junior

Recall the picture: a span is a reference plus a length over memory someone else owns, and a slice is another window on the same data.

for a middle

Explain the backings, arrays, strings, stackalloc and native memory, and point to exactly which calls copy: ToArray, ToString and CopyTo.

for a senior

Show how you keep a hot path span-only and convert to a string or array once, where data must outlive the method, and why ref struct rules force that boundary.

for a principal

Frame spans as an API design choice: one ReadOnlySpan<T> parameter serves every backing, so public parsing helpers can accept spans without callers allocating.

## What a span is `Span<T>` and `ReadOnlySpan<T>` (in `System`, since C# 7.2) describe a **contiguous run of `T` values that somebody else owns**. Inside, a span is just two things: - a **managed reference** to the first element (or a native pointer turned into one), - a **length**, the number of elements it covers. That is the whole representation in `Span.cs`: a `ref T` field and an `int` field. A span allocates nothing, frees nothing and has no capacity; it is a window onto memory that already exists. `ReadOnlySpan<T>` is the same window, but its indexer returns a `ref readonly T`, so code holding it cannot write through it. ## What a span can point at | Backing memory | How you get the span | Writable? | |---|---|---| | An array `T[]` | `array.AsSpan()`, `array.AsSpan(start, length)`, or an implicit conversion | Yes, `Span<T>` | | A `string` | `text.AsSpan()` or the implicit conversion to `ReadOnlySpan<char>` | No, strings are immutable | | Stack memory | `Span<byte> buf = stackalloc byte[16];` | Yes | | Native memory | `new Span<T>(void* pointer, int length)` inside `unsafe` code | Yes | | Part of another span | `span.Slice(start, length)` or `span[start..end]` | Same as the parent | The point of the type is that **one API serves all of these**. A method that takes `ReadOnlySpan<char>` can parse a whole string, a piece of a string, a `char[]` buffer or stack memory, and it never has to know which. ## Why slicing does not copy `Slice(int start, int length)` checks the bounds, then builds a new span whose reference is moved forward by `start` elements and whose length is `length`. No element is touched. The C# range syntax, `span[1..4]`, lowers to the same `Slice` call. The cost of a slice is therefore the same whether the span covers ten elements or ten million. Two consequences follow from it being a view: 1. **Writes go through.** Write to a `Span<int>` taken from an array and the array changes, because there is only one copy of the data. 2. **Bounds are still checked.** `array.AsSpan(2, 5)` on a three-element array throws `ArgumentOutOfRangeException`; a span does not trade away safety for speed. ## Where a copy does happen A span copies only when you ask it to: - `ToArray()` allocates a new `T[]` and copies into it; the source comment in `Span.cs` warns that it "heap allocates". - `ToString()` on a `Span<char>` or `ReadOnlySpan<char>` allocates a new `string` holding those characters. On any other `T` it returns a description such as `System.ReadOnlySpan<Int32>[3]`, not the elements. - `CopyTo(destination)` and `TryCopyTo` copy into memory you provide. That is the habit spans teach: slice freely, and turn a span into a `string` or array **once**, at the point where something must outlive the current method. Measured on this SDK, slicing a log line 1,000 times allocated nothing per slice, while 1,000 `Substring` calls of the same length allocated 48,000 bytes. ## Where a span may live `Span<T>` is a `ref struct`, because it can point at stack memory that dies when the method returns. The compiler therefore keeps it on the stack: it cannot be a field of a class, cannot be boxed to `object`, and cannot be kept across an `await`. Those rules have a lesson of their own on ref structs; when data must be stored or passed through async code, `Memory<T>` is the storable counterpart, also covered separately. ## Common mistakes - **Expecting a copy.** Code that slices a buffer, then "resets" the original array, is surprised when the slice changes too. If you need an independent snapshot, call `ToArray()`. - **Printing a non-char span.** `Console.WriteLine(span)` on a `Span<int>` shows the type name and length, not the numbers; loop over it or copy it to an array to print elements. - **Forgetting the read-only form.** A method that only reads should take `ReadOnlySpan<T>`. `Span<T>` converts to it implicitly, arrays and strings convert to it, so the read-only parameter accepts the widest set of callers. - **Assuming lists convert.** `List<T>` has no conversion to `Span<T>`; its backing array is private and can be replaced when the list grows, which is exactly why a span over it would be fragile. - **Using `ToString()` early.** Turning every slice into a string as soon as it is found throws away the benefit. Keep slices as spans until the one place where a value must be stored. ## Interview angle A good answer sounds like "a typed pointer plus a length with bounds checks". It names at least the array, the string and `stackalloc` as backings, shows that a slice shares memory, and knows that `ToArray` and `ToString` are where the allocation comes back.

  • What is the difference between Span<T> and ReadOnlySpan<T>, and why does string.AsSpan() return the read-only one?
    Both are views with a reference and a length. `ReadOnlySpan<T>`'s indexer returns `ref readonly T`, so you cannot assign through it. `string.AsSpan()` returns `ReadOnlySpan<char>` because strings are immutable, and a writable span over a string would let code change a string other code may share. A `Span<T>` converts implicitly to `ReadOnlySpan<T>`, so methods should accept the read-only form when they only read.
  • If you slice a span and later need that piece as a string stored in an object, what do you do?
    Call `ToString()` on the slice at that point. It allocates one string with just those characters, and the string can be stored anywhere. The span itself cannot be kept in a class field because it is a `ref struct`, so the copy is the deliberate hand-over from the stack-only view to a heap object.
  • Does indexing a span skip bounds checks the way a raw pointer would?
    No. The span indexer, `Slice` and the range syntax all check bounds and throw `IndexOutOfRangeException` or `ArgumentOutOfRangeException`. The speed comes from not copying and not allocating, not from removing checks; skipping checks needs `MemoryMarshal` or `Unsafe`, which belong to unsafe-code work.

  • Says Span<T> copies the array into a new buffer when created.
  • Thinks Slice allocates a smaller array for the selected elements.
  • Believes a span can only wrap arrays, never strings or stackalloc memory.
  • Assumes writing through a span leaves the original array unchanged.
  • Claims span indexing has no bounds checks, like a raw pointer.
  • Expects ToString on a Span<int> to print the elements.