Phase 19 of 30 · Topic 19.5

`Unsafe` & `MemoryMarshal` Low-Level Reinterpretation Casts

1Concept

`MemoryMarshal.Cast<TFrom, TTo>` reinterprets the bytes of a span from one struct type to another without memory copying or pointer arithmetic.

2Architecture Diagram

Span<int> (2 elements = 8 bytes):    [ 0x11223344, 0x55667788 ]
                                             │
                       MemoryMarshal.Cast<int, byte>()
                                             ▼
Span<byte> (8 elements = 8 bytes):   [ 0x44, 0x33, 0x22, 0x11, 0x88, 0x77, 0x66, 0x55 ]

3Code Example

C# 13 & .NET 9
using System;
using System.Runtime.InteropServices;

public class MemoryMarshalDemo
{
    public static void Main()
    {
        int[] ints = [0x12345678, 0x00AABBCC];
        Span<int> intSpan = ints;

        // Zero-copy byte cast
        Span<byte> byteSpan = MemoryMarshal.AsBytes(intSpan);
        Console.WriteLine($"Reinterpreted Byte Span Length: {byteSpan.Length} bytes");
    }
}

4Expected Output

Reinterpreted Byte Span Length: 8 bytes

5Key Takeaways

  • `MemoryMarshal.AsBytes` provides instant byte views for network serialization.
  • Must operate on unmanaged blittable structs.
  • 100x faster than BitConverter conversions.