skip to content

In C# 12, how does an [InlineArray] struct replace an unsafe fixed-size buffer such as fixed byte Tag[16], and what does it make safe?

level: seniorimportance: nice to knowfreq 18%

answer

  1. the runtime repeats one field
  2. primitives only versus any type
  3. indexer, span and foreach
  4. out-of-range reads the neighbour

basics

~20 s

[InlineArray(16)] on a one-field struct makes the runtime repeat that field 16 times inline. C# 12 then gives bounds-checked indexing, Span<T> conversion and foreach in safe code, for any element type; fixed buffers need unsafe, primitives only and are unchecked.

solid answer

~40 s

A fixed-size buffer, `public fixed byte Tag[16];`, stores 16 bytes inside an `unsafe struct`, but it accepts only twelve primitive element types (CS1663 otherwise), needs an `unsafe` context for every access and does no bounds checking, so `Tag[16]` quietly reads the next field. C# 12 with .NET 8 added `[InlineArray(N)]`: you declare a struct with exactly one instance field, the runtime lays that field out N times in a row, and the compiler treats the struct as an array of N elements. Indexing is checked (CS9166 for a constant index out of range, `IndexOutOfRangeException` at run time), the struct converts to `Span<T>` and `ReadOnlySpan<T>`, `foreach` works, and the element type can be any type usable as a type argument, including references. No `unsafe` keyword is needed.

code

csharp · 33 lines
csharp
using System.Runtime.CompilerServices;

var header = new FrameHeader { Version = 2 };
for (int i = 0; i < FrameHeader.TagLength; i++) header.Tag[i] = (byte)('A' + i);

Console.WriteLine(header.Checksum());
Console.WriteLine(Unsafe.SizeOf<FrameHeader>());

Span<byte> tag = header.Tag;          // converts to Span<byte> over the struct's own storage
Console.WriteLine(tag.Length);

try { int i = 20; header.Tag[i] = 0; }
catch (IndexOutOfRangeException) { Console.WriteLine("index 20 rejected"); }

struct FrameHeader
{
    public const int TagLength = 16;
    public int Version;
    public TagBuffer Tag;

    public readonly int Checksum()
    {
        int sum = Version;
        foreach (byte b in Tag) sum = sum * 31 + b;   // foreach works on an inline array
        return sum;
    }
}

[InlineArray(FrameHeader.TagLength)]
struct TagBuffer
{
    private byte _element0;
}

go deeper

for a junior

Recall that both features store N elements inside a struct, and that only the inline array works in safe code with any element type.

for a middle

Explain the one-field rule, the runtime repeating the field, and the indexer, span conversion and foreach the compiler adds.

for a senior

Show the bug an unchecked fixed buffer allows, migrate it to an inline array, and know the declaration errors CS9169, CS9167 and CS9166.

for a principal

Prefer inline arrays for new fixed-length data so bounds checks stay on, and keep fixed buffers only where existing interop layouts require them.

## The problem both features solve Sometimes a struct must **hold a fixed number of elements inside itself** rather than a reference to an array: a 16-byte tag in a frame header that is checksummed or copied as one block, a small ring of samples in a hot struct, a header whose layout matches a binary format. A field of type `byte[]` stores only a reference, and the elements live in a separate heap object. ## The old way: fixed-size buffers C# has long offered **fixed-size buffers** inside unsafe structs: ```csharp unsafe struct LegacyHeader { public int Version; public fixed byte Tag[16]; public int Crc; } ``` Their limits are what makes them unsafe: - **`unsafe` everywhere.** The struct and every access need an unsafe context, and the project needs `AllowUnsafeBlocks`. - **Primitive elements only.** The element type must be `bool`, `byte`, `short`, `int`, `long`, `char`, `sbyte`, `ushort`, `uint`, `ulong`, `float` or `double`; anything else fails with CS1663. - **No bounds checks.** `h.Tag[16]` on a 16-element buffer compiles and reads the first byte of `Crc`; writing there corrupts it. - **Struct fields only.** A fixed-size buffer can be an instance field of a struct and nothing else (CS1642). ## What [InlineArray] does `System.Runtime.CompilerServices.InlineArrayAttribute` arrived with .NET 8, and C# 12 understands it: ```csharp [InlineArray(16)] struct TagBuffer { private byte _element0; } ``` The **runtime** replicates the single field 16 times, laid out sequentially like array elements, so `TagBuffer` is 16 bytes and a `FrameHeader` with an `int` and a `TagBuffer` is 20. The **compiler** then lets you treat a variable of that type as an array: 1. **Indexing** with `int`, `Index` or `Range`, all bounds-checked: a constant index out of range is a compile error, CS9166 (*Index is outside the bounds of the inline array*), and a computed one throws `IndexOutOfRangeException`. 2. **Conversion** to `Span<T>` and `ReadOnlySpan<T>` over the struct's own storage, so every span API works on it with no copy. 3. **`foreach`** over the elements. 4. **Any element type** that can be a generic type argument, including `string` and other references, which the GC tracks normally. Pointer types are excluded. All of it is safe code. ## Rules for declaring one The compiler validates each `[InlineArray]` type: - exactly one instance field (CS9169, *Inline array struct must declare one and only one instance field.*); - a length greater than zero (CS9167); - no explicit layout (CS9168); - a plain struct, not a `record struct` (CS9259). A span conversion needs a variable: converting a method's return value to `Span<T>` fails with CS9164, because the temporary is not an assignable variable. ## Side by side | | `fixed byte Tag[16]` | `[InlineArray(16)]` struct | |---|---|---| | Needs `unsafe` / `AllowUnsafeBlocks` | yes | no | | Element types | 12 primitive types | any type usable as a type argument | | Bounds checks | none | CS9166 at compile time, `IndexOutOfRangeException` at run time | | Span conversion, `foreach` | through a pointer only | built in | | Where it can live | instance field of a struct | a struct, usable anywhere a struct is | | Origin | part of the original unsafe-code feature set | C# 12 with .NET 8 | ## Migrating a fixed buffer Replacing `public fixed byte Tag[16];` in an existing header struct is mechanical: 1. Declare `[InlineArray(16)] struct TagBuffer { private byte _element0; }`; the field name is private and arbitrary. 2. Change the field to `public TagBuffer Tag;` and drop `unsafe` from the struct if nothing else needs it. 3. Replace pointer loops with indexing, a `foreach`, or a `Span<byte>` taken from the field (`Span<byte> tag = header.Tag;`), which works because `header` is a variable. 4. Re-run the tests that cover the boundaries: an index that used to read the next field now throws, which may reveal a latent bug rather than introduce one. The struct's size and layout stay the same: 16 bytes in a row, so a checksum over the whole header or a copy of it behaves exactly as before. ## When fixed buffers still appear Existing interop structs and code that already lives inside an unsafe region keep fixed buffers, and pointer code can take a buffer's address directly. For new code that just needs N elements inline, an `[InlineArray]` struct gives the same layout without giving up bounds checks. Passing either kind to native code is interop, which belongs to the material on the .NET runtime.

  • Can a C# [InlineArray] struct hold strings, and could a fixed-size buffer?
    An inline array can: its single field may be any type usable as a type argument, so `[InlineArray(4)] struct NameBuffer { private string? _first; }` stores four GC-tracked references inline. A fixed-size buffer cannot; `fixed string Names[4]` fails with CS1663 because only twelve primitive element types are allowed.
  • Why does Span<byte> t = Get().Tag; fail to compile when Tag is an [InlineArray] field?
    A span over an inline array points into the struct's own storage, so the struct must be a variable that outlives the span. `Get()` returns a temporary copy, and the compiler reports CS9164 (cannot convert because the expression is not an assignable variable). Store the result in a local first, then convert the local's field.
  • What does indexing an [InlineArray] with a computed index out of range do in C#?
    It throws `IndexOutOfRangeException`, exactly like an array. With a constant index the compiler catches it earlier, with CS9166. That check is the main safety gain over a fixed-size buffer, where an out-of-range index silently reads or writes the neighbouring field.

  • An InlineArray struct still needs unsafe and AllowUnsafeBlocks
  • Fixed-size buffers check indexes and throw IndexOutOfRangeException
  • A fixed-size buffer can hold any struct type, including references
  • InlineArray allocates a hidden heap array behind the struct
  • An InlineArray struct may declare several fields to repeat