C# allowed stack allocation of arrays using stackalloc
, but initializing the values required a separate loop or multiple assignment statements, making the code verbose.
C# 7.3 adds support for array initializer syntax with stackalloc
, allowing you to allocate and initialize stack-based arrays in a single concise expression, similar to regular array initialization.
Code
C#
Span<int> numbers = stackalloc int[] { 1, 2, 3, 4, 5 };
Span<byte> rgb = stackalloc byte[] { 0xFF, 0x00, 0x80 };
// Can also omit the type
Span<int> values = stackalloc[] { 10, 20, 30 };
C#
Span<int> numbers = stackalloc int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
Span<byte> rgb = stackalloc byte[3];
rgb[0] = 0xFF;
rgb[1] = 0x00;
rgb[2] = 0x80;
Notes
- The array size is inferred from the number of initializer elements
- Works with both
Span<T>
and unsafe pointer types - The type can be omitted if it can be inferred from the target type
- Stack-allocated memory is automatically reclaimed when the method returns
- Be cautious with large allocations as stack space is limited (typically ~1MB)