csharplang/proposals/csharp-7.3/stackalloc-array-initializers.md
Bill Wagner f69b012846 markdown fixes for 7.3 proposals
These were:

1. adding `csharp` as the language identifier.
1. making relative links to content published on docs.microsoft.com
1. small grammar fixes.
2019-03-07 16:04:57 -05:00

1.8 KiB

Stackalloc array initializers

Summary

Allow array initializer syntax to be used with stackalloc.

Motivation

Ordinary arrays can have their elements initialized at creation time. It seems reasonable to allow that in stackalloc case.

The question of why such syntax is not allowed with stackalloc arises fairly frequently.
See, for example, #1112

Detailed design

Ordinary arrays can be created through the following syntax:

new int[3]
new int[3] { 1, 2, 3 }
new int[] { 1, 2, 3 }
new[] { 1, 2, 3 }

We should allow stack allocated arrays be created through:

stackalloc int[3]				// currently allowed
stackalloc int[3] { 1, 2, 3 }
stackalloc int[] { 1, 2, 3 }
stackalloc[] { 1, 2, 3 }

The semantics of all cases is roughly the same as with arrays.
For example: in the last case the element type is inferred from the initializer and must be an "unmanaged" type.

NOTE: the feature is not dependent on the target being a Span<T>. It is just as applicable in T* case, so it does not seem reasonable to predicate it on Span<T> case.

Translation

The naive implementation could just initialize the array right after creation through a series of element-wise assignments.

Similarly to the case with arrays, it might be possible and desirable to detect cases where all or most of the elements are blittable types and use more efficient techniques by copying over the pre-created state of all the constant elements.

Drawbacks

Alternatives

This is a convenience feature. It is possible to just do nothing.

Unresolved questions

Design meetings

None yet.