Consider the following methods (fiddle):
void test(Span<int> param)
{
//Fail, the stackalloc'ed buffer could be exposed.
param = stackalloc int[10];
}
void test2(Span<int> param)
{
//OK
Span<int> local = stackalloc int[10];
}
I don't understand why param = stackalloc int[10];
produces the error:
A result of a
stackalloc
expression of type 'Span' cannot be used in this context because it may be exposed outside of the containing method
Span
is a ref struct
but (despite its name) it is still a value-type so any modification to param
won't be reflected on the caller object.
I think of param
as a local variable with an initial value and I don't see why test2
compiles while test
doesn't.
How can the returned value of stackalloc int[10]
in test
escape the scope of the method?
As a result, Span<T> instances can only live on the stack, not on the heap.
- I lack the knowledge to make it coherent as an answer. – BrookbrookeSpan
parameters, where it more than likely is an actual mistake. – Mundaystackalloc[0]
(whatever that would means)? – Bailableparam
is something that could potentially be returned by the method and thus we cannot assignstackalloc
'ed expression to it. Just link a local initialized to anysafe-to-escape
value. Thank you! – Friarbird