In .NET normally arrays are reference types and an array declared as part of a structure doesn’t physically exist inside the struct.
Only a reference to the array is placed inside the structure, which points to the original location of the array on the heap.
Hence declaring a C++ style fixed-size structure was difficult in earlier versions of C#.
Table of Contents
Fixed Size Buffer In C#
In C# 2.0, it’s now possible to declare arrays in structure as fixed-sized inside unsafe code blocks. Fixed arrays will typically be part of a structure that’s passed to a native API.
public unsafe struct CharArray
Buffers with a set size. The fixed statement in C# allows you to create a data structure buffer with a fixed size array. All that’s required is for the array type to be of short, int, long, sbyte, ushort, uint, ulong, float, double, char, bool or byte.
When writing methods that interact with data sources from other programming languages or platforms, fixed size buffers come in handy.
C# Fixed Size Buffer Sample
Lets see how we can define fixed size array in C# to have them in struct
public unsafe struct DataStructSample
public int aNumber;
public fixed float aArray;
Benefits Of Fixed Size Buffer In C#
As in C++, the size of the built-in arrays must be maintained. The same is true for fixed size buffers in C#. This data type is similar to inline array in functionality.
Fixed size buffers in C# will someway benefits like static code checking. Because they aren’t a standard part of C#, they’re a pain to use. As a result, it’s probably best to keep struct’s size as part of it. Either that or use a collection such as Array in C#. Fixing the buffer and then making it part of other structures with other data could be an alternative solution.
This article covered C# Fixed Size Buffer. When writing methods that interact with data sources from other programming languages or platforms, fixed size buffers come in handy. Any attributes or modifiers allowed for regular struct members can be applied to the fixed array. Hope you found this article helpful.