-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
CS8353 when trying to initialize Span<T> variable using stackalloc outside of its declaration #25118
Comments
This would also be useful if Span<SomeStruct> span;
if (RuntimeHelpers.TryEnsureSufficientExecutionStack(list.Count * PUT_HERE_YOUR_STRUCT_SIZE))
{
span = stackalloc SomeStruct[size];
}
else
{
span = ArrayPool<SomeStruct>.Shared.Rent(size);
} |
Uninitialized span local is classified as ordinary "returnable" span. Then you cannot assign stackallocated spans to it. If you initialize with |
The usability issues that come from this behavior are discussed in dotnet/csharplang#1130 For the time being this is ByDesign. We may need to introduce a feature to make such declarations easier to do. |
Version Used:
Visual Studio Community 2017 Preview
15.6.0 Preview 6.0
Steps to Reproduce:
Program.cs
App.csproj
Expected Behavior:
This feels like it should be considered safe. The
Span<T>
never escapes this method.Actual Behavior:
CS8353: A result of a stackalloc expression of type 'Span<byte>' cannot be used in this context because it may be exposed outside of the containing method
.Workaround:
Joining the declaration and assignment will make the error go away, but that doesn't look amazing in this situation (and this situation doesn't really seem all that esoteric)Edit: a better workaround for a more "full" version of this repro, from the comments below:
My Own Guesses:
I'm guessing the analyzer is a bit paranoid here, because it's a lot easier to reject cases like this than to prove that there are no possible ways for this
Span<T>
to escape whenever it's stack-allocated.The text was updated successfully, but these errors were encountered: