Skip to content
Tutorials Center
My learning

Topics

Lesson 164 of 182 ยท Advanced C#

Pointers, stackalloc and Low-level Memory

Go deep on low-level C#: ref locals, stackalloc, unsafe pointers, fixed buffers, InlineArray, the Unsafe and MemoryMarshal classes, endianness and the pitfalls to avoid.

Most C# is memory-safe by design: arrays check bounds, the garbage collector decides when objects die, and you cannot turn an int into a pointer by accident. That safety costs a little (bounds checks, allocations), and a few jobs need to peek beneath it: parsing binary formats, high-throughput networking, interop with C, graphics and game engines, number crunching on big buffers.

The earlier lesson on unsafe code and interop introduced pointers and fixed. This lesson is the deep end: the toolbox of low-level features, from the almost-safe (ref locals, Span<T>, stackalloc) to the really unsafe (raw pointers, Unsafe.As), and, more importantly, how to decide which one you need. A good rule: use the safest tool that does the job, and measure before you reach for a sharper one.

The ladder from safe to unsafe

Rung Tools Checked by
Safe arrays, List<T>, strings Runtime (bounds, types)
Almost safe ref locals and returns, Span<T>, stackalloc into a span, [InlineArray] Compiler (lifetime rules) and runtime (bounds)
Library-level unsafe Unsafe, MemoryMarshal, CollectionsMarshal You
Language-level unsafe unsafe blocks, pointers, fixed, stackalloc into a pointer You

Start at the top and climb only when you have a reason.

ref locals and ref returns

A normal local variable holds a value. A ref local is an alias for another variable: reading or writing it reads or writes the original, without copying. A method can also return a ref to an array element or a field. The runtime and compiler guarantee the reference never outlives what it points to.

C# ref locals and ref returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With large structs this avoids copying and lets you modify the element in place. If you had written Cell first = cells[0]; first.Value = 7;, you would have changed a copy and the array would be untouched. This is one of the most common reasons to use ref in performance-sensitive code (ref readonly and in parameters give the read-only version).

stackalloc and the lifetime rules

You met stackalloc in Span, Memory and slicing: memory taken from the current method's stack frame, freed automatically on return, assigned to a Span<T>. The compiler enforces the dangerous part: the span cannot escape the method that created it, because the memory is gone once the method returns.

C# Returning a stackalloc span (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops you with error CS8352: Cannot use variable 'buffer' in this context because it may expose referenced variables outside of their declaration scope. That is Span<T> doing its job. The fix is to move the buffer to the caller, so the memory outlives the method:

C# The caller owns the buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Passing the buffer down the call chain is always safe. Passing it up is what the compiler forbids. If you assign stackalloc to a pointer (int* p = stackalloc int[4]) instead of a span, these protections vanish and you can return a dangling pointer. That is a reason to always prefer the span form.

Pointers and unsafe blocks

To use pointers you must opt in. In a project that means one line in the .csproj (our editor already has it enabled):

XML
<!-- Read-only: your project file -->
<PropertyGroup>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

Then you wrap pointer code in an unsafe block or mark a method or type unsafe. The operators are borrowed from C: &x takes the address, *p follows a pointer, p[i] indexes, p + 1 moves by one element, and p->Field reads a field of the struct p points to.

C# Looking at an int one byte at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first byte is 4, not 1: x86 and ARM machines store the least-significant byte first (little-endian). When you read binary files or network data, always check which byte order the format uses. BinaryPrimitives.ReadInt32BigEndian and its siblings read and write either order explicitly, with no pointers and no guessing.

fixed: pinning a managed object

The garbage collector can move objects in memory to compact the heap. A pointer into a managed array would then point at the wrong place. fixed pins the object (tells the GC not to move it) for the length of the block and gives you a pointer.

C# fixed on arrays, strings and spans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Keep fixed blocks short. A pinned object can fragment the heap, and the pointer is only valid inside the block: never store it in a field or return it.

Fixed buffers and inline arrays

Sometimes a struct needs an array inside itself, laid out in the same block of memory (like char name[8] in C). Two features do this.

Fixed-size buffers (old, C# 1) require unsafe and give you a pointer to the first element. Inline arrays (C# 12, .NET 8) are the modern, safe version: mark a struct with [InlineArray(n)] and give it one field. The compiler repeats the field n times in a row and lets you index the struct like an array and convert it to a Span<T>.

C# InlineArray: a small array inside a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The whole Rgba value is four bytes, stored inline: no heap allocation, no pointer to follow, bounds-checked access. Inline arrays are how libraries such as the .NET runtime itself build small fixed-size buffers. Use a fixed-size buffer only to match a C struct you pass to native code, and check interop for how those layouts line up.

The Unsafe class

The System.Runtime.CompilerServices.Unsafe class gives you unsafe operations without pointer syntax, and it works with managed references that the GC tracks, so objects can still move safely. Its methods are small but sharp:

  • Unsafe.As<TFrom, TTo>(ref x) reinterprets a reference as another type, with no check.
  • Unsafe.Add(ref x, n) moves a reference forward by n elements, with no bounds check.
  • Unsafe.SizeOf<T>() gives the size of a type.
  • Unsafe.AreSame, Unsafe.AsRef, Unsafe.ReadUnaligned, Unsafe.WriteUnaligned and more.

Often there is a safe built-in that does the same thing. To see a float's bits you can use BitConverter.SingleToUInt32Bits, but Unsafe.As shows the idea:

C# Reinterpreting bits with Unsafe.As

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

1.5f is stored as 0x3FC00000: sign 0, exponent 127, mantissa 1000.... Prefer the named API (BitConverter) when it exists; it says what you mean.

MemoryMarshal and CollectionsMarshal

MemoryMarshal (in System.Runtime.InteropServices) works with spans. It lets you view the same memory as different types, and reach inside collections.

C# Viewing the same memory as bytes and ints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

CollectionsMarshal.AsSpan(list) is the fast way to loop over a list, but the span is only valid until the list changes size (it may allocate a new internal array). Adding to the list while you still hold the span leaves the span pointing at the old array. That is the typical mistake with every API in this section: a view is only valid while the thing it views stays put.

Pitfalls professionals know

  • No bounds checks means silent corruption. A Span<int> throws IndexOutOfRangeException when you index past the end. A pointer, Unsafe.Add or fixed buffer does not: it reads or overwrites whatever happens to be next in memory, sometimes crashing at once, sometimes corrupting data that is found later. Bugs in unsafe code may show up far from the cause.
  • Dangling pointers. A pointer to a stackalloc buffer dies when the method returns. A pointer from fixed dies at the closing brace. Never store either.
  • Alignment. Some CPUs fault or slow down on unaligned reads. When parsing bytes at arbitrary offsets use Unsafe.ReadUnaligned or BinaryPrimitives, not a cast to int*.
  • Endianness and struct layout. Reading a struct straight from bytes assumes the file's byte order and padding match your machine's. Formats and network protocols should be read field by field with explicit byte order.
  • Stack overflow. Large stackalloc calls (hundreds of kilobytes) can crash the process, and the crash cannot be caught. Use a threshold and fall back to an array pool.
  • Type punning with Unsafe.As on reference types (casting an object to an unrelated class) defeats the type system and can corrupt the heap. Avoid it outside runtime-level libraries.
  • Security. Memory-safety bugs are among the most serious security problems in software. Unsafe code in a web-facing service deserves code review and fuzz tests.

Do not use unsafe code because you believe it is "faster". Measure first, as described in measuring and improving performance. Modern .NET removes bounds checks in many loops automatically, and Span<T> code is usually within a few percent of pointer code while staying safe.

When to use what

  • Prefer Span<T>, stackalloc into a span, ref locals and [InlineArray]: almost-safe, compiler-checked lifetimes.
  • Reach for MemoryMarshal, CollectionsMarshal and Unsafe in measured hot paths, behind a small well-tested helper.
  • Use pointers and fixed when you pass memory to native code (interop) or implement a low-level data structure.
  • Avoid unsafe code in ordinary business logic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a ref local variable do?

    A ref local refers to existing storage, such as an array element. Writing through it changes the original with no copy.
  2. 2. Why does 'Span<int> s = stackalloc int[4]; return s;' fail to compile?

    The compiler's lifetime rules (error CS8352) stop a span over stack memory from escaping the method, because the memory is released on return.
  3. 3. What does the fixed statement do?

    The GC may relocate objects. fixed pins the object for the duration of the block and gives you a stable pointer.
  4. 4. What is the key difference between indexing a Span<int> and indexing an int* pointer?

    A span throws IndexOutOfRangeException for an invalid index. A pointer happily reads or writes whatever memory is at that address.
  5. 5. What does [InlineArray(4)] on a struct with one byte field give you?

    The compiler repeats the field four times in the struct's own memory and supplies indexing and Span conversion, with no separate allocation.

Summary

  • Climb from safe to unsafe only when you must: ref, Span<T>, stackalloc, [InlineArray], then Unsafe/MemoryMarshal, then pointers.
  • ref locals and returns alias existing storage; the compiler enforces lifetimes (a span over stackalloc cannot escape its method).
  • Pointers need AllowUnsafeBlocks and an unsafe context; fixed pins managed objects only for its block.
  • [InlineArray(n)] (C# 12) gives a safe fixed-size buffer inside a struct.
  • Unsafe, MemoryMarshal and CollectionsMarshal reinterpret and reach inside memory without checks: a view is valid only while the data does not move or resize.
  • The classic bugs are silent out-of-bounds access, dangling pointers, alignment, endianness and oversized stackalloc. Measure before using any of this.

Next: IL, JIT and Tiered Compilation