Posts

Showing posts with the label stackalloc

Why does a zero-length stackalloc make the C# compiler happy to allow conditional stackallocs?

41 6 The following "fix" is very confusing to me; the scenario here is conditionally deciding whether to use the stack vs a leased buffer depending on the size - a pretty niche but sometimes-necessary optimization, however: with the "obvious" implementation (number 3, deferring definite assignment until we actually want to assign it), the compiler complains with CS8353: A result of a stackalloc expression of type 'Span<int>' cannot be used in this context because it may be exposed outside of the containing method The short repro (a complete repro follows) is: // take your pick of: // Span<int> s = stackalloc[0]; // works // Span<int> s = default; // fails // Span<int> s; // fails if (condition) { // CS8353 happ...