proposals/rejected/fixed-sized-buffers.md
Champion issue: https://github.com/dotnet/csharplang/issues/1314
Provide a general-purpose and safe mechanism for declaring fixed sized buffers to the C# language.
Today, users have the ability to create fixed-sized buffers in an unsafe-context. However, this requires the user to deal with pointers, manually perform bounds checks, and only supports a limited set of types (bool, byte, char, short, int, long, sbyte, ushort, uint, ulong, float, and double).
The most common complaint is that fixed-size buffers cannot be indexed in safe code. Inability to use more types is the second.
With a few minor tweaks, we could provide general-purpose fixed-sized buffers which support any type, can be used in a safe context, and have automatic bounds checking performed.
One would declare a safe fixed-sized buffer via the following:
public fixed DXGI_RGB GammaCurve[1025];
The declaration would get translated into an internal representation by the compiler that is similar to the following
[FixedBuffer(typeof(DXGI_RGB), 1024)]
public ConsoleApp1.<Buffer>e__FixedBuffer_1024<DXGI_RGB> GammaCurve;
// Pack = 0 is the default packing and should result in indexable layout.
[CompilerGenerated, UnsafeValueType, StructLayout(LayoutKind.Sequential, Pack = 0)]
struct <Buffer>e__FixedBuffer_1024<T>
{
private T _e0;
private T _e1;
// _e2 ... _e1023
private T _e1024;
public ref T this[int index] => ref (uint)index <= 1024u ?
ref RefAdd<T>(ref _e0, index):
throw new IndexOutOfRange();
}
Since such fixed-sized buffers no longer require use of fixed, it makes sense to allow any element type.
NOTE:
fixedwill still be supported, but only if the element type isblittable
v2 encoding to hide the fields from old compiler.readonly fields, if supported) will have impact on metadata. It will be bound by the number of arrays of different sizes in the given app.ref math is not formally verifiable (since it is unsafe). We will need to find a way to update verification rules to know that our use is ok.Manually declare your structures and use unsafe code to construct indexers.
readonly? (with readonly indexer)fixed keyword necessary?foreach?Link to design notes that affect this proposal, and describe in one sentence for each what changes they led to.