C# Fixed Buffer
In this tutorial, you'll learn about C# Fixed Buffer. We cover key concepts, practical examples, and best practices.
You need a struct with an inline array of fixed size — for interop, performance, or memory layout control. A regular array field is a reference (pointer) to heap memory. A fixed buffer stores the array data directly inside the struct, avoiding indirection.
Wrong
public struct PixelData
{
public byte[] R; // Heap-allocated reference — not inline
public byte[] G;
public byte[] B;
}
Output: Each PixelData instance holds three references to heap arrays. The struct is 24 bytes (on 64-bit) plus heap allocation. Not contiguous.
Right
public unsafe struct PixelData
{
public fixed byte R[256]; // 256 bytes inline
public fixed byte G[256]; // 256 bytes inline
public fixed byte B[256]; // 256 bytes inline
}
Output: PixelData is 768 bytes contiguous — all data inline, no heap allocation, no indirection.
Fixed buffers require unsafe context and can only be used in struct types:
unsafe struct ColorPalette
{
public fixed int Colors[16]; // 16 ints inline (64 bytes)
}
// Usage
var palette = new ColorPalette();
palette.Colors[0] = 0xFF0000; // Direct inline access
Prevention
- Use fixed buffers in structs for interop with native code (matching C
structlayouts). - Use fixed buffers for performance-critical inline storage (graphics, audio, networking).
- Use
Span<T>or regular arrays when heap allocation is acceptable. - Use
fixedstatement to get a pointer to the buffer:fixed (int* ptr = palette.Colors). - Use
sizeof()to get the size of the inline buffer. - Enable
AllowUnsafeBlocksin.csproj— fixed buffers require unsafe. - Use
stackallocfor temporary stack buffers instead of fixed buffers in methods.
Common Mistakes with fixed buffer
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Fixed buffers are used in DodaZIP for inline archive header parsing. For more C# interop patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro