C# 8 Stackalloc in Nested Expressions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

The stackalloc operator allocates a memory block in the stack. A memory block is created during the execution of the method, and it is automatically deleted when the method is returned.

  • The Span<T>, ReadOnlySpan<T>, and Memory<T> are ref struct instances guaranteed to be allocated on the stack, and therefore won't affect the garbage collector.
  • Using Span, it was also possible to avoid declaring the stackalloc statements that are directly assigned to Span or ReadOnlySpan as unsafe.

In C# 8.0, if the result of a stackalloc expression is Span<T> or ReadOnlySpan<T>, you can use the stackalloc expression in other expressions as shown in the below example.

Span<int> numbers = stackalloc[] { 1, 2, 3, 4, 5, 6 };

var index = numbers.IndexOfAny(stackalloc[] { 4, 8, 12 });

Console.WriteLine(index);   // output: 3  

As you can see the nested stackalloc in the above code. Let's consider another example simple example.

string input = "This is a simple string \r\n";
ReadOnlySpan<char> trimmedChar = input.AsSpan().Trim(stackalloc[] { ' ', '\r', '\n' });


In the above example, it trims the input string from three special characters.

Got any C# 8 Question?