skip to content

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%

answer

  1. reinterpret, never copy
  2. leftover bytes vanish
  3. native byte order and alignment
  4. safe-looking signatures

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.

solid answer

~40 s

`MemoryMarshal.Cast<byte, uint>(span)` returns a span over the same memory with length `bytes / 4`: no copy, no endianness conversion, no alignment check, and leftover bytes silently disappear. Beyond a generic `struct` constraint, its only check is a run-time `ArgumentException` if either type contains references. `Unsafe.Add(ref r, n)` offsets a managed `ref` by n elements with no bounds check, so it can step past the end of a slice; `Unsafe.As` reinterprets a ref or object with no type check, and `MemoryMarshal.CreateSpan` trusts the length you pass. None of these signatures uses pointers, so they compile in a project with `AllowUnsafeBlocks` off, although misuse corrupts memory just like pointer code. Prefer `BinaryPrimitives.ReadUInt32LittleEndian` or `MemoryMarshal.Read<T>`, which check the length, for parsing binary formats.

code

csharp · 22 lines
csharp
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// No AllowUnsafeBlocks, no unsafe keyword: all of this compiles as "safe" code.
byte[] header = [1, 0, 0, 0, 2, 0, 0, 0, 0xFF, 0xEE];   // 10 bytes

ReadOnlySpan<uint> words = MemoryMarshal.Cast<byte, uint>(header);
Console.WriteLine($"words: {words.Length}");                 // 2: the last 2 bytes are silently dropped
Console.WriteLine($"word0 native: {words[0]}");               // byte order of this machine
Console.WriteLine($"word0 LE: {BinaryPrimitives.ReadUInt32LittleEndian(header)}");
Console.WriteLine($"little-endian machine: {BitConverter.IsLittleEndian}");

Span<int> all = [10, 20, 30, 40];
Span<int> firstTwo = all[..2];
ref int past = ref Unsafe.Add(ref MemoryMarshal.GetReference(firstTwo), 2);
Console.WriteLine($"past the slice: {past}");                 // reads all[2]; no bounds check

try { MemoryMarshal.Cast<byte, Entry>(header); }
catch (ArgumentException ex) { Console.WriteLine(ex.GetType().Name + ": " + ex.Message); }

readonly record struct Entry(int Id, string Name);

go deeper

for a junior

Recall that MemoryMarshal and Unsafe reinterpret memory without copying, and that they skip checks ordinary span code performs.

for a middle

Explain Cast's truncated length, native byte order and alignment caveat, and why Unsafe.Add can step outside a span.

for a senior

Spot unchecked offsets and silent truncation in review, and replace them with BinaryPrimitives or MemoryMarshal.Read where the speed gain is not measured.

for a principal

Treat these APIs as unsafe code for policy purposes, because the compiler switch does not catch them, and enforce that with an analyzer.

## Two classes of unchecked operations `System.Runtime.InteropServices.MemoryMarshal` and `System.Runtime.CompilerServices.Unsafe` are the base class library's low-level toolbox. The library uses them internally to implement spans, string search and vectorized code, and they are public so that performance-critical code can do the same. Both work on **managed references (`ref T`) and spans rather than pointers**, which is why they look like safe code. Consider an interop-free checksum over a frame header: read the header's bytes as 32-bit words and add them up. ## What MemoryMarshal.Cast checks, and what it skips `MemoryMarshal.Cast<TFrom, TTo>(Span<TFrom>)` (and its `ReadOnlySpan` overload) returns a new span over **the same memory**, reinterpreted as `TTo`: - **Checked:** both types must be value types without references. That is a generic `struct` constraint plus a run-time test; a struct with a `string` field throws `ArgumentException` (*Only value types without pointers or references are supported.*). - **Not checked: length.** The new length is `bytes / sizeof(TTo)`, rounded down. A 10-byte header cast to `uint` gives 2 words, and the last 2 bytes are silently ignored. - **Not checked: byte order.** The words are read in the machine's native order. A format defined as big-endian produces wrong values on little-endian hardware, with no error. - **Not checked: alignment.** The method's own documentation says it is supported only on platforms that allow misaligned access or when the memory is aligned by other means. - **No copy.** Writes through the `Span<uint>` change the original bytes. ## Unsafe.Add, Unsafe.As and friends | API | What it skips | Typical failure | |---|---|---| | `Unsafe.Add<T>(ref T, int)` | bounds checks | reads or writes past the end of a slice or array | | `Unsafe.As<TFrom, TTo>(ref TFrom)` | type and size checks | reinterprets memory as a larger or unrelated type | | `Unsafe.As<T>(object)` | the cast check | treats an object as a type it is not, corrupting memory | | `MemoryMarshal.GetReference(span)` | the empty check | a ref to element 0 of an empty span must never be read | | `MemoryMarshal.CreateSpan(ref T, int)` | the length and the lifetime | a span longer than the data, or outliving it | `GetReference` documents that for an empty span the returned ref may point anywhere and must never be dereferenced. `CreateSpan` warns that its length is not checked and that span-aware languages do not validate the returned span's lifetime. A typical slice bug looks harmless: a method receives `Span<int> firstTwo = all[..2]` and walks it with `Unsafe.Add(ref MemoryMarshal.GetReference(firstTwo), i)` for `i` up to a count computed elsewhere. When the count is 3, `firstTwo[2]` would have thrown `IndexOutOfRangeException`, but the `Unsafe.Add` version quietly returns `all[2]`, which belongs to the caller. If the slice sat at the end of an array, the read would leave the array entirely. ## Why AllowUnsafeBlocks does not flag them The `AllowUnsafeBlocks` switch and the `unsafe` keyword guard **pointer syntax**: pointer types, `&`, `*`, `fixed`, pointer `stackalloc`, function pointers, fixed-size buffers. `Unsafe.Add(ref T, int)` has an ordinary generic signature with a `ref` parameter, so the compiler sees a normal method call. The consequences are the same as pointer code (out-of-bounds access, type confusion, memory corruption), but nothing in the project file announces them. A team that bans unsafe code through the compiler switch alone has not banned these calls. ## Safer tools for the same jobs 1. **`BinaryPrimitives.ReadUInt32LittleEndian(ReadOnlySpan<byte>)`** reads one word in a stated byte order and throws `ArgumentOutOfRangeException` if the span is too short. 2. **`MemoryMarshal.Read<T>(ReadOnlySpan<byte>)`** checks that the span holds at least `sizeof(T)` bytes and reads unaligned, though still in native byte order. 3. **Plain span indexing** keeps bounds checks; the JIT often removes them in simple loops. 4. **`[InlineArray]` structs** give fixed-length inline storage with checked indexing. ## Using them responsibly When a measurement justifies `MemoryMarshal` or `Unsafe`, keep the call next to the check that makes it correct: validate the length is a multiple of the element size (or handle the tail), state the byte order in a comment and convert with `BinaryPrimitives.ReverseEndianness` where needed, compute every `Unsafe.Add` offset from a length checked in the same method, and test with lengths 0, 1, an odd size and the maximum.

  • How would you make a C# checksum over a header's uint words correct on any byte order?
    Either read each word with `BinaryPrimitives.ReadUInt32LittleEndian` (or `BigEndian`, matching the format), or keep `MemoryMarshal.Cast` for speed and, when `BitConverter.IsLittleEndian` differs from the format, convert each word with `BinaryPrimitives.ReverseEndianness`. Also handle a length that is not a multiple of four instead of letting Cast drop the tail.
  • What does MemoryMarshal.GetReference return for an empty Span<T>, and why does it matter?
    A ref to where element 0 would be. The documentation says it may or may not be null and must never be dereferenced; it is meant for pinning or address arithmetic. Code that does `Unsafe.Add(ref MemoryMarshal.GetReference(span), i)` without first checking `span.Length` can read memory it does not own.

  • MemoryMarshal.Cast throws when the byte count is not a multiple of the target size
  • MemoryMarshal.Cast converts the data to little-endian for you
  • Unsafe.Add is bounds-checked because it works on refs, not pointers
  • Turning off AllowUnsafeBlocks stops all memory-unsafe code from compiling
  • MemoryMarshal.Cast copies the bytes into a new uint buffer