C# unsafe code and fixed buffers: bound every access
A fixed-size buffer stores a declared number of primitive elements inside a struct. It is useful when a low-level interface requires that representation. For ordinary application data, a managed array keeps indexing checked and avoids pointer lifetime work. This tutorial compares an inline buffer with pinning an existing array, then checks two compiler failures.
Prerequisites: basic structs and arrays. The examples were compiled and run with the pinned .NET SDK 10.0.402, target net10.0, and effective C# 14.0. Nullable analysis and warnings as errors were enabled. This article covers the established unsafe model; it does not enable C# 15 preview memory-safety rules.
Enable unsafe compilation deliberately
Set the project property AllowUnsafeBlocks to true for the working example. That compiler permission and an unsafe context serve different purposes: the property permits unsafe compilation, while the context permits pointer and fixed-buffer operations in source. Neither validates your indices or pointer lifetime. See Microsoft’s compiler options and unsafe code reference.
A struct buffer and a pinned array
Run this complete program with unsafe compilation enabled:
using System;
public unsafe struct SampleBuffer
{
public fixed int Values[3];
}
public static class Program
{
public static unsafe void Main()
{
SampleBuffer buffer = default;
for (int i = 0; i < 3; i++)
buffer.Values[i] = i + 1;
Console.WriteLine(buffer.Values[0] + buffer.Values[1] + buffer.Values[2]);
int[] managed = { 7, 11, 13 };
fixed (int* first = managed)
{
int sum = 0;
for (int i = 0; i < managed.Length; i++)
sum += first[i];
Console.WriteLine(sum);
}
}
}
Expected output:
6
31
Values is a fixed-size buffer field containing three integers within each SampleBuffer value. Its length is part of the declaration. Fixed-size buffers are instance fields of structs; their element types are restricted primitive types. They are not managed array objects. Here buffer is a local value, so accessing its buffer does not require a fixed statement. The first loop visits exactly the three declared positions.
The second half starts with a managed array. A garbage collector may move managed objects, so the fixed statement pins the array for its block and initializes first to the address of its first element. Pointer indexing reads the three values while the array is pinned. Keep every use of that pointer inside the block: after the block, the pin ends, so retaining a copied address would not keep the array in place. Microsoft’s fixed statement reference explains this lifetime.
The shared word fixed describes two distinct constructs: a fixed-size buffer declaration specifies inline storage; a fixed statement temporarily prevents relocation. This example demonstrates a buffer in a local struct value; it does not demonstrate taking a pointer to a buffer field inside a movable managed object.
Check the boundaries yourself
Pointer indexing does not perform the array bounds checks provided by normal managed indexing. Both loop bounds are deliberate: three is the buffer’s declared capacity, and managed.Length is the array’s length. Reading or writing past those ranges is invalid and can corrupt memory. The example does not attempt an out-of-range access. A successful compilation proves syntax and type rules, not memory safety.
Keep unsafe code small and document who owns the storage, how long it remains valid, which length is trusted, and whether a native API may retain a pointer. This program makes no native call and establishes no binary interoperability contract: real APIs also require their documented element representation, layout and lifetime rules. Prefer normal managed indexing whenever it meets the requirement; this article makes no speed claim.
Two failures that catch setup and declaration mistakes
Compile the complete working program again with AllowUnsafeBlocks disabled. It fails with CS0227, rather than producing output. Adding the unsafe keyword alone does not enable the project compiler option.
With unsafe compilation enabled, this separate program still fails:
public unsafe class InvalidBuffer
{
public fixed int Values[3];
}
public static class Program { public static void Main() { } }
The compiler reports CS1642: fixed-size buffer fields may only be members of structs. Changing the containing type to a class does not turn an inline buffer into a managed array. Use an array field when that is the representation you need. These failures were checked separately from the successful run; consult Microsoft’s unsafe-code diagnostics for the compiler rules.
Choose the smallest unsafe boundary
Choose a fixed-size buffer when a documented storage contract calls for inline primitive elements. Use a fixed statement when a pointer must temporarily refer into movable managed storage. In both cases, review every index and lifetime, and keep a managed alternative unless the low-level requirement justifies the additional responsibility.