Skip to content

Why can't a stackalloc expression be assigned to a pointer field? #3894

Answered by 333fred
jnm2 asked this question in General
Discussion options

You must be logged in to vote

This is because stackalloc in C# behaves differently when it's a top-level expression vs a nested expression. Previous to C# 7.2, stackalloc was only allowed as top-level expression, and could not be nested. You can see remnants of this here: https://github.com/dotnet/csharplang/blob/master/spec/unsafe-code.md#stack-allocation. For legacy reasons, when you use stackalloc as a variable initializer today, you get a char* back as the natural type, and we add an implicit conversion to Span<T> if the thing you assign to is a Span<T>. However, for any other context, we do the safer thing and stackalloc always returns a Span<T>, instead of a T*. This means that in your nested object initializer,…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by jnm2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants