Unsafe Code
By the end of this lesson you'll slice arrays and strings with zero allocations using Span<T> , hand big buffers back to the runtime with ArrayPool , and understand exactly when raw pointers and unsafe are worth the risk — and when they absolutely aren't.
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
Think of an array as a long bookshelf . A Span<T> is a window frame you place over part of that shelf: you can read and rearrange the books you can see through the frame, but you never lift the shelf or copy a single book. Moving the frame to a different section ( Slice ) costs nothing — you're just looking somewhere else on the same shelf. Everything in this lesson is about working through that window instead of photocopying the books, because copying is what makes programs slow and creates garbage. unsafe pointers, by contrast, are like taking the shelf off the wall and carrying it by hand — far more freedom, far more chances to drop it.
📊 The High-Performance Toolbox
Type
Lives on
What it gives you
Use when
Span<T>
Stack only
No-copy, writable window over memory
Hot loops, slicing, parsing — inside one method
ReadOnlySpan<T>
Read-only window (e.g. over a string)
Viewing strings/data you must not change
Memory<T>
Heap-safe
Span you can store in a field / use across await
Async pipelines, buffers held over time
stackalloc
Stack
A small buffer with zero GC cost
Tiny, short-lived scratch space
ArrayPool<T>
Heap (pooled)
Rent & return big arrays instead of allocating
Large reusable buffers in hot paths
int* / unsafe
Raw pointer
Direct memory access, no bounds checks
P/Invoke & rare interop only
Rule of thumb: reach for the row that's highest in this table that solves your problem. Span<T> covers the vast majority of "make it faster" needs safely ; pointers should be your last resort, not your first.
1. Span<T> — a No-Copy Window Over Memory
A Span<T> is a small struct that holds just two things: where some contiguous memory starts and how many items it covers. It never owns or copies the data — it points at memory you already have (an array, a string, or a stack buffer). That's why slicing is free: Slice just produces a new "where/how many" pair over the same bytes. Because it's bounds-checked, you still get the safety of an array index without the cost of a copy. Read this worked example, run it, then you'll write your own.
Your turn. The program below is almost complete — fill in the three blanks marked ___ using the hints, then run it. You'll slice the middle of an array and sum it without copying a single element .
Now a second exercise that brings in two more no-copy tools: stackalloc (a tiny buffer placed on the stack, with no garbage-collector cost) and a ReadOnlySpan<char> view onto part of a string. Both run perfectly safely — no unsafe flag needed.
2. Memory<T> & ArrayPool — Buffers That Outlive a Method
Span<T> has one big restriction: it can only live on the stack, so you can't store it in a class field or carry it across an await (more on why below). When you need a buffer that outlives a single method — an async download, say — use Memory<T> , the heap-safe sibling. You slice it the same no-copy way, then call .Span for fast access when you're ready to touch the bytes. And when you need big buffers repeatedly, ArrayPool<T> lets you rent an array and return it, so the garbage collector never sees the churn.
🔎 Deep Dive: why Span<T> is a ref struct
Span<T> is declared as a ref struct , which is the compiler's way of saying "this value must stay on the stack." That single rule is the reason for every restriction you'll hit:
- It can't be a field of a normal class. Class instances live on the heap, and a stack-only value can't be stored there.
- It can't be boxed (assigned to object or an interface) — boxing puts it on the heap, which is forbidden.
- It can't survive an await or yield . Those suspend the method and stash locals on the heap; a stack-only Span can't be stashed there. Use Memory<T> across await instead.
Why bother with such a strict type? Because the stack-only guarantee is exactly what makes a Span safe and fast: the runtime knows the memory it points at can't outlive the current stack frame, so it needs no extra bookkeeping. The restrictions are the feature.
3. Unsafe Code & Pointers — Read It, Rarely Write It
C# lets you drop to raw pointers inside an unsafe block: & takes a variable's address, int* is "pointer to an int", and fixed pins a managed array so the garbage collector won't move it while you hold a pointer into it. This is real, low-level power — and almost always the wrong tool. It needs the /unsafe compiler flag ( <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in your .csproj ), it removes bounds checking, and a single slip is undefined behaviour. Study the example below to recognise pointer code in the wild; the expected output is in the comments because the in-browser runner may not enable unsafe.
Putting It Together: an Allocation-Free CSV Parser
Here's a small but genuinely useful program that uses this lesson's core skill. "100,200,300".Split(',') would allocate an array and three new strings. The version below walks a ReadOnlySpan<char> over the original text and parses each field in place — zero extra allocations . It runs safely, no unsafe needed.
Notice int.Parse accepts a ReadOnlySpan<char> directly — most modern .NET parsing APIs do, which is what makes allocation-free pipelines possible.
Pro Tips
- 💡 Reach for Span<T> before unsafe : it matches pointer speed but keeps bounds checking. unsafe should be reserved for P/Invoke and true interop.
- 💡 Keep stackalloc small. The stack is tiny (~1 MB). A good ceiling is a few hundred elements; check a size limit before allocating per request.
- 💡 Always pair Rent with Return, ideally in a finally block. A rented array that's never returned is effectively a leak from the pool's view.
- 💡 Take ReadOnlySpan<char> parameters for string-processing helpers — callers can pass a substring with no copy, and you can't accidentally mutate it.
- 💡 Use Memory<T> at API boundaries, Span<T> inside the hot loop. Convert with .Span only when you're ready to crunch the data.
Common Errors (and the fix)
- "CS8345: Field or auto-implemented property cannot be of type 'Span<int>'" — a ref struct can't be a class field. Store a Memory<T> (or the array) in the field and convert to a Span locally.
- "CS4007: 'await' cannot be used on an expression of type ... Span" / a Span you can't use after await — Spans can't cross an await . Hold a Memory<T> across the await and call .Span after it resumes.
- A Span can't be boxed — assigning one to object or an interface fails to compile because boxing would put a stack-only type on the heap. Keep it as its concrete type.
- Stack overflow from a big stackalloc — stackalloc int[10_000_000] blows the ~1 MB stack and crashes the process. Cap the size, or rent a heap buffer from ArrayPool<T> instead.
- "CS0227: Unsafe code may only appear if compiled with /unsafe" — add <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to a <PropertyGroup> in your .csproj .
- Garbage values / random crashes from pointer arithmetic — reading *(p + i) past the array length is undefined behaviour; there are no bounds checks. This is exactly why Span<T> is the safer default.
📋 Quick Reference
Task
Code
Result
Span over an array
arr.AsSpan()
no-copy view
Slice (start, length)
span.Slice(2, 4)
4 items from index 2
View a string
"hi".AsSpan()
ReadOnlySpan<char>
Stack buffer
stackalloc int[3]
Span<int>, no GC
Heap-safe buffer
arr.AsMemory()
Memory<int>
Rent / return
pool.Rent(n) / Return(a)
reused array
Address of a variable
int* p = &x;
unsafe only
Pin an array
fixed (int* p = arr)
GC won't move it
Frequently Asked Questions
Q: When should I actually use unsafe and pointers?
Rarely. Realistic cases are calling native libraries via P/Invoke, marshalling fixed-layout structs, or a profiled hot path where Span<T> genuinely isn't enough. For everyday slicing, parsing, and buffers, Span<T> gives you the same speed with bounds checking — prefer it every time.
Q: What's the difference between Span<T> and Memory<T> ?
Span<T> is stack-only and the fastest to use, but can't be a field or cross an await . Memory<T> can live on the heap (fields, async), and you get a Span from it with .Span when you need to work with the data.
Only if you ask for too much. It places memory on the stack (no GC cost), but the stack is small — about 1 MB. Keep allocations to a few hundred elements; a large or unbounded stackalloc overflows the stack and crashes the process. For anything big, use ArrayPool<T> .
No. Slice just creates a new Span pointing at part of the same memory. Writing through the slice changes the original array. To get an independent copy you must explicitly call .ToArray() .
Mini-Challenge: Sum a Sub-Range, No Copy
No blanks this time — just a brief and an outline. Use a Span<int> to add up a slice of the array without copying it. Build it, run it, and check your output against the expected line in the comments.
🎉 Lesson Complete
- ✅ Span<T> / ReadOnlySpan<T> are no-copy windows over memory; Slice is free
- ✅ stackalloc gives a tiny GC-free buffer — but keep it small or you overflow the stack
- ✅ Memory<T> is the heap-safe sibling for fields and await ; ArrayPool<T> reuses big buffers
- ✅ Span is a ref struct : it can't be a field, be boxed, or cross an await — by design
- ✅ unsafe /pointers/ fixed are powerful but a last resort — reserved for interop and rare hot paths
- ✅ Next lesson: IDisposable & Resource Management — clean up files, sockets, and unmanaged handles correctly
Practice quiz
What does a Span<T> represent?
- A copy of an array on the heap
- A thread-safe collection
- A no-copy window over contiguous memory you already have
- A pointer that needs the /unsafe flag
Answer: A no-copy window over contiguous memory you already have. A Span<T> is a small struct holding where memory starts and how many items it covers. It copies nothing — it just views memory you already own.
Does span.Slice(start, length) copy the underlying data?
- No, it creates a new window over the same memory
- Yes, it allocates a new array
- Only for strings
- Only when length is large
Answer: No, it creates a new window over the same memory. Slice just produces a new start/length pair over the same bytes — writing through the slice changes the original array.
Why can't a Span<T> be stored as a field of a normal class?
- It is sealed
- It is always read-only
- Fields cannot be generic
- It is a ref struct that must stay on the stack, but class instances live on the heap
Answer: It is a ref struct that must stay on the stack, but class instances live on the heap. Span<T> is a ref struct, meaning it must live on the stack. A class instance lives on the heap, so a stack-only value cannot be stored as its field.
Which type should you use to hold a buffer across an await?
- Span<T>
- Memory<T>
- ReadOnlySpan<char>
- stackalloc
Answer: Memory<T>. Span<T> cannot survive an await because it is stack-only. Memory<T> is the heap-safe sibling; call .Span on it when you are ready to touch the data.
What does stackalloc give you?
- A small buffer placed on the stack with no GC cost
- A heap array that needs garbage collection
- A pinned pointer
- A pooled array you must return
Answer: A small buffer placed on the stack with no GC cost. stackalloc allocates a small buffer on the stack (backing a Span), so there is no 'new', no heap allocation, and no garbage-collector cost.
What is the main risk of an over-large stackalloc?
- It rounds numbers
- It leaks memory to the pool
- It overflows the ~1 MB stack and crashes the process
- It boxes the values
Answer: It overflows the ~1 MB stack and crashes the process. The stack is small (about 1 MB). A large or unbounded stackalloc overflows it and crashes the process — cap the size or use ArrayPool<T>.
With ArrayPool<T>, what must you always do after Rent?
- Dispose the array
- Return the array to the pool, ideally in a finally block
- Pin it with fixed
- Copy it with ToArray
Answer: Return the array to the pool, ideally in a finally block. Every Rent must be paired with a Return (ideally in finally). A rented array never returned is effectively a leak from the pool's perspective.
In unsafe code, what does the fixed statement do?
- Rounds a pointer to an alignment boundary
- Marks a value as read-only
- Allocates on the heap
- Pins a managed array so the GC won't move it while you hold a pointer
Answer: Pins a managed array so the GC won't move it while you hold a pointer. fixed pins a managed array in place so the garbage collector cannot relocate it while you hold a raw pointer into it.
What does the & operator do in unsafe C#?
- Bitwise AND only
- Takes the address of a variable
- Dereferences a pointer
- Declares a pointer type
Answer: Takes the address of a variable. In unsafe context & takes the address of a variable (e.g. int* ptr = &value;). The * operator dereferences a pointer.
When is reaching for unsafe pointers actually warranted over Span<T>?
- For everyday array slicing
- Whenever you want speed
- For P/Invoke and rare interop where Span genuinely isn't enough
- For parsing strings
Answer: For P/Invoke and rare interop where Span genuinely isn't enough. Span<T> matches pointer speed while keeping bounds checking, so it covers most needs. unsafe is reserved for P/Invoke, fixed-layout marshalling, and rare profiled hot paths.
Continue this course
- Previous: Memory Management
- Next: IDisposable & Resource Management