proposals/csharp-8.0/nested-stackalloc.md
stackalloc in nested contexts[!INCLUDESpecletdisclaimer]
Champion issue: https://github.com/dotnet/csharplang/issues/1412
We modify the section Stack allocation (§12.8.22 Stack allocation) of the C# language specification to relax the places when a stackalloc expression may appear. We delete
local_variable_initializer_unsafe
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression ']'
;
and replace them with
primary_no_array_creation_expression
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression? ']' array_initializer?
| 'stackalloc' '[' expression? ']' array_initializer
;
Note that the addition of an array_initializer to stackalloc_initializer (and making the index expression optional) was an extension in C# 7.3 and is not described here.
The element type of the stackalloc expression is the unmanaged_type named in the stackalloc expression, if any, or the common type among the elements of the array_initializer otherwise.
The type of the stackalloc_initializer with element type K depends on its syntactic context:
K*.System.Span<K>.The stackalloc conversion is a new built-in implicit conversion from expression. When the type of a stackalloc_initializer is K*, there is an implicit stackalloc conversion from the stackalloc_initializer to the type System.Span<K>.