Span<T>, Memory<T> & Zero-Allocation Code
Work with slices of existing memory using Span<T> and ReadOnlySpan<T> so hot-path parsing can avoid unnecessary substring and array allocations.
Part 1: What You Will Learn
Work with slices of existing memory using Span<T> and ReadOnlySpan<T> so hot-path parsing can avoid unnecessary substring and array allocations.
- Create a `ReadOnlySpan<char>` over an existing string.
- Slice a span without creating new strings.
- Parse numbers directly from a span.
- Use `stackalloc` for small temporary buffers that should not live on the managed heap.
Project setup: Create a .NET 10 Console App. No additional package is required.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
static (int Id, decimal Price) ParseProductLine(string line)
{
ReadOnlySpan<char> span = line.AsSpan();
int comma = span.IndexOf(',');
ReadOnlySpan<char> idSpan = span[..comma];
ReadOnlySpan<char> priceSpan = span[(comma + 1)..];
int id = int.Parse(idSpan);
decimal price = decimal.Parse(priceSpan);
return (id, price);
}
var product = ParseProductLine("101,299.90");
Console.WriteLine($"ID: {product.Id}");
Console.WriteLine($"Price: {product.Price:C}");
// Small temporary buffer on the stack.
Span<int> marks = stackalloc int[] { 72, 81, 90, 68 };
int total = 0;
foreach (int mark in marks)
total += mark;
Console.WriteLine($"Average: {(double)total / marks.Length:F1}");Part 3: How the Code Works
- `AsSpan()` creates a view over the original string rather than a new copy.
- Range slicing such as `span[..comma]` returns another span over the same underlying memory.
- `int.Parse(ReadOnlySpan<char>)` and `decimal.Parse(ReadOnlySpan<char>)` can parse directly from slices.
- `stackalloc` is suitable only for small, short-lived buffers; large allocations should remain on the managed heap or use pooling.
Part 4: Mini Project & Practice
Mini project: parse `StudentId,Mark` lines using spans. Compare the span-based version with a version using `Split(',')` and later benchmark both in Lesson 36.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 32.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition