C# 12/13 `[InlineArray]` Fixed-Size Buffer Architecture
1Concept
`[InlineArray(N)]` creates a contiguous fixed-size struct buffer directly on the stack or inline inside an object, avoiding separate heap array allocations while maintaining safe indexing.
2Architecture Diagram
[InlineArray(4)] Struct Layout in RAM: ┌──────────────┬──────────────┬──────────────┬──────────────┐ │ Element [0] │ Element [1] │ Element [2] │ Element [3] │ (Contiguous 16 Bytes on Stack) └──────────────┴──────────────┴──────────────┴──────────────┘
3Code Example
C# 13 & .NET 9
using System;
using System.Runtime.CompilerServices;
[InlineArray(4)]
public struct FixedBuffer4<T>
{
private T _element0;
}
public class InlineArrayDemo
{
public static void Main()
{
var buffer = new FixedBuffer4<int>();
buffer[0] = 10;
buffer[1] = 20;
buffer[2] = 30;
buffer[3] = 40;
Console.WriteLine($"Inline Buffer Items: {buffer[0]}, {buffer[1]}, {buffer[2]}, {buffer[3]}");
Console.WriteLine("Stored 100% contiguously on the thread stack without heap pointer dereferencing.");
}
}4Expected Output
Inline Buffer Items: 10, 20, 30, 40 Stored 100% contiguously on the thread stack without heap pointer dereferencing.
5Key Takeaways
- ✓`[InlineArray]` provides high-speed fixed buffers without `unsafe` pointers.
- ✓Enforces strict bounds checks preventing buffer overruns.
- ✓Used heavily throughout .NET 9 internals (e.g. `DefaultInterpolatedStringHandler`).