Using stackalloc in nested expressions
With C# 7, we started using Span<T>
, ReadOnlySpan<T>
, and Memory<T>
because they are ref struct
instances that are guaranteed to be allocated on the stack, and therefore won't affect the garbage collector. Thanks to Span
, it was also possible to avoid declaring the stackalloc
statements that are directly assigned to Span
or ReadOnlySpan
as unsafe:
Span<int> nums = stackalloc int[10];
Starting from C# 8, the compiler widens the use of stackalloc
to any expression expecting Span
or ReadOnlySpan
. In the following example, the test trims the input
string from three special characters, obtaining the string specified in the expected
variable:
string input = " this string can be trimmed \r\n";
var expected = "this string can be trimmed";
ReadOnlySpan<char> trimmedSpan = input.AsSpan()
.Trim(stackalloc[] { ' ', '\r', '\n' });
string result...