skip to content

Low-Allocation Code

Span<T>, Memory<T>, ref structs, stackalloc and pooled buffers let C# slice and parse without allocating. Interviewers ask what a ref struct cannot do and why.

on this pageshow

explore

questions

22

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.
open as a page

In a C# async method that reads a stream into a buffer, why must the buffer be a Memory<byte> rather than a Span<byte>?

level: middleimportance: must knowfreq 50%

basics

~20 s

Span<byte> is a stack-only ref struct, so it cannot be kept across an await, which hoists live locals into a heap state machine. Memory<byte> is an ordinary struct that can live there; take its .Span only between awaits.

open as a page

In a C# HTTP log parser, how do you read each line's status code and duration with ReadOnlySpan<char> instead of string.Split?

level: middleimportance: must knowfreq 52%

basics

~20 s

View the line as a ReadOnlySpan<char>, split it into a stackalloc'd Span<Range> with MemoryExtensions.Split (.NET 8), and pass the slices straight to int.Parse and double.Parse, which accept spans. Nothing allocates per line unless you call ToString.

open as a page

In C#, what is a ref struct such as Span<T>, and which uses of an ordinary struct does the compiler reject for it?

level: juniorimportance: should knowfreq 48%

basics

~20 s

A ref struct is a stack-only struct, which lets it safely hold a span or a ref field. It cannot be boxed, be an array element, be a field of a class or ordinary struct, or be captured by a lambda.

open as a page

In C#, what does Span<byte> buffer = stackalloc byte[16]; allocate, and why does it compile without the unsafe keyword?

level: juniorimportance: should knowfreq 40%

basics

~20 s

It reserves 16 bytes in the current method's stack frame and wraps them in a bounds-checked Span<byte>. The block is discarded when the method returns, never touches the GC, and is safe code because the span knows its length.

open as a page

With .NET's ArrayPool<byte>.Shared, why can Rent(50_000) return a 65,536-byte array holding old data, and what must the caller track?

level: middleimportance: should knowfreq 42%

basics

~20 s

ArrayPool<byte>.Shared rounds requests up to power-of-two buckets and reuses returned arrays without clearing them, so Rent(50_000) can return 65,536 bytes with a previous renter's data. The caller must track how many bytes it actually uses.

open as a page

In C#, why does a ref struct PacketReader compile in a synchronous method but fail when used after an await or a yield return?

level: middleimportance: should knowfreq 40%

basics

~20 s

Locals used after an await or yield return are hoisted into a state machine that can live on the heap, where a ref struct may not go. Since C# 13 a ref struct local compiles only if it is never used after one (CS4007).

open as a page

In C#, how does a method returning ref to a sensor array's largest element let callers update it, and what may it never return?

level: middleimportance: should knowfreq 35%

basics

~20 s

A ref return hands back an alias to existing storage; a caller who keeps it in a ref local writes straight into the array. Only storage that outlives the call may be returned, never a local (CS8168) or a by-value parameter (CS8166).

open as a page

In C# 14, what do the new implicit span conversions let you write with arrays, strings and ReadOnlySpan<T> that C# 13 rejected?

level: middleimportance: should knowfreq 35%

basics

~20 s

C# 14 makes array-to-span, span-to-ReadOnlySpan and string-to-ReadOnlySpan<char> built-in implicit conversions. Arrays and strings can now call extension methods declared on spans, generic methods taking ReadOnlySpan<T> infer T from an array, and ReadOnlySpan<string> converts to ReadOnlySpan<object>.

open as a page

In C#, why can `method == "GET"` return false for a ReadOnlySpan<char> sliced from a log line, and how do you compare span contents?

level: middleimportance: should knowfreq 38%

basics

~20 s

The == operator on spans checks whether both point at the same memory with the same length, not whether they hold the same characters. Compare contents with SequenceEqual, MemoryExtensions.Equals with a StringComparison, or the constant pattern span is "GET".

open as a page

In C# unsafe code, why must a byte* into a managed byte[] come from a fixed statement, and what does pinning cost?

level: middleimportance: should knowfreq 35%

basics

~20 s

The GC can move a byte[] while compacting and never updates raw pointers. fixed pins the array for the statement's body so the pointer stays valid; the cost is an immovable object, which hinders compaction when pins are long or many.

open as a page

A C# upload service pools 64 KB buffers with ArrayPool<byte>.Shared, and forwarded chunks sometimes carry another upload's bytes; which rental bugs cause this?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Two code paths share one array: a double Return let the pool hand it to two renters, or a stored Memory<byte> or unawaited task still used it after Return. ArrayPool<T>.Shared detects neither; return exactly once, after the last use.

open as a page

Why does C# reject reader.ReadInto(scratch) with CS8350 when reader is a ref PacketReader and scratch is stackalloc memory, and how does scoped fix it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

The compiler assumes ReadInto might store its Span<byte> argument in the reader, which outlives the stackalloc buffer, so the call could leak stack memory (CS8350, CS8352). Declaring the parameter scoped Span<byte> promises it never escapes, and the call compiles.

open as a page

A C# log parser calls IndexOfAny with a char[] of six separators on every line; why does .NET 8's SearchValues<char> help, and how do you use it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Beyond five values, IndexOfAny prepares its search from the value list on each call. SearchValues.Create (.NET 8) does that analysis once: cache the instance in a static readonly field and pass it to IndexOfAny, ContainsAny or SplitAny.

open as a page

A C# grayscale converter calls stackalloc inside its per-row loop and crashes with 'Stack overflow.' on large frames; why, and how do you size the buffer safely?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Each stackalloc in the loop takes a new block that is released only when the method returns, so per-row buffers pile up until the stack runs out. Allocate one capped buffer before the loop and fall back to the heap.

open as a page

As a lead on a C# codebase, when would you allow ArrayPool<T> pooling, and how would your team catch pool misuse before it reaches production?

level: principalimportance: should knowfreq 18%

basics

~20 s

Allow pooling only on hot paths where measured buffer allocation matters, keep each rental under one owner (try/finally or an IMemoryOwner<T>), and catch misuse with review rules, an injected checking pool in tests and the pool's event source in production.

open as a page

As a lead, would you allow unsafe code in a C# codebase, and if so where, under what review, and how would you enforce the boundary?

level: principalimportance: should knowfreq 25%

basics

~20 s

Allow it only where a measurement shows safe spans cannot match it: in one small assembly with AllowUnsafeBlocks, behind a validated span-based API, with mandatory review and edge-case tests, and with Unsafe and MemoryMarshal banned elsewhere because the switch misses them.

open as a page

In .NET, what does IMemoryOwner<T> from MemoryPool<T>.Shared.Rent add over a raw ArrayPool<T> rental, and who must dispose it?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

IMemoryOwner<T> turns ownership into an object: whoever holds it must either call Dispose, which returns the pooled array, or hand it on and stop using it. Consumers receive only Memory<T>, which carries no ownership.

open as a page

In C# 13 and later, how can a ref struct PacketReader implement an interface and be passed to generic code without ever being boxed?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Since C# 13 a ref struct may implement an interface, but converting it to that interface is rejected because it would box. Generic code opts in with where T : IByteSource, allows ref struct and then calls the interface members on T directly.

open as a page

In C# 11 and later, what does a ref field in a ref struct let you build, and which rules does the compiler enforce?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

A ref field stores a managed reference, letting a ref struct point at a variable it does not own; Span<T> is a ref T field plus a length. Only ref structs may declare one (CS9059), and it cannot refer to a ref struct (CS9050).

open as a page

In C# 12, how does an [InlineArray] struct replace an unsafe fixed-size buffer such as fixed byte Tag[16], and what does it make safe?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

[InlineArray(16)] on a one-field struct makes the runtime repeat that field 16 times inline. C# 12 then gives bounds-checked indexing, Span<T> conversion and foreach in safe code, for any element type; fixed buffers need unsafe, primitives only and are unchecked.

open as a page

In .NET, what checks do MemoryMarshal.Cast<byte, uint> and Unsafe.Add skip, and why does code calling them compile without AllowUnsafeBlocks?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

MemoryMarshal.Cast<byte, uint> reinterprets bytes as uints, checking only that neither type holds references; it drops leftover bytes and ignores byte order and alignment. Unsafe.Add moves a ref with no bounds check. Neither uses pointer syntax, so AllowUnsafeBlocks never sees them.

open as a page