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?