Arrays
An array provides contiguous indexed storage for elements of one type, with an explicit choice between stack and heap allocation.
Array types and allocation
T[] is the array type. The element count belongs to the allocation expression and may be computed at runtime.
int count = GetCount();
int[] temporary = int[count];
int[] persistent = new int[count];
T[n] allocates temporary array storage in the current stack frame. new T[n] allocates array storage on the heap.
Indexing
Use array[index] to read or write an element. The index must be an integer expression.
persistent[0] = 10;
persistent[1] = persistent[0] + 5;
int first = persistent[0];
Stack array lifetime
A stack array is local to the function that allocates it. It may be indexed and assigned locally, but it cannot be returned, passed to another function, or stored in a field or another escaping value.
int SumPair(int left, int right)
{
int[] values = int[2];
values[0] = left;
values[1] = right;
return values[0] + values[1];
}
Heap array lifetime
A heap array may be passed, returned or stored. Its owner releases the allocation explicitly with free.
void Fill(int[] values)
{
values[0] = 42;
}
int[] values = new int[16];
Fill(values);
free(values);
Length and native boundaries
The T[] value does not carry its element count. Code that needs bounds keeps the length separately and passes it explicitly. The same pointer-and-length shape is used at a C ABI boundary.
void Process(int[] values, nuint length);
extern void ProcessNative(int* values, nuint length);