How to Use Span in C#: Syntax, Example, and Tips
In C#,
Span<T> is a stack-only type that provides a safe way to work with contiguous memory regions without allocations. You use it by creating a Span<T> over arrays, slices, or stack memory to efficiently access or modify data.Syntax
The basic syntax to declare a Span<T> is:
Span<T> span = new Span<T>(array);- creates a span over an existing array.Span<T> slice = span.Slice(start, length);- creates a sub-span from an existing span.Span<T> stackSpan = stackalloc T[length];- creates a span over stack-allocated memory.
T is the type of elements the span holds.
csharp
int[] numbers = {1, 2, 3, 4, 5}; Span<int> span = new Span<int>(numbers); Span<int> slice = span.Slice(1, 3); Span<int> stackSpan = stackalloc int[5];
Example
This example shows how to create a Span<int> from an array, modify its elements, and print the results. It demonstrates efficient memory access without copying the array.
csharp
using System; class Program { static void Main() { int[] numbers = {10, 20, 30, 40, 50}; Span<int> span = numbers; // Modify elements through the span for (int i = 0; i < span.Length; i++) { span[i] += 5; } // Print modified array foreach (var num in numbers) { Console.Write(num + " "); } } }
Output
15 25 35 45 55
Common Pitfalls
Common mistakes when using Span<T> include:
- Trying to store a
Span<T>in a field of a class, which is not allowed because it is a stack-only type. - Using
Span<T>with types that are not blittable or safe for memory operations. - Forgetting that
Span<T>does not allocate memory; it only provides a view over existing memory.
Example of wrong usage and correct usage:
csharp
class WrongUsage { // Error: Span<T> cannot be a field in a class // Span<int> spanField; } class CorrectUsage { void Method() { int[] data = {1, 2, 3}; Span<int> span = data; // Use span inside method only } }
Quick Reference
Span<T> Cheat Sheet:
| Operation | Description | Example |
|---|---|---|
| Create from array | Creates a span over an existing array | Span |
| Slice | Creates a sub-span from an existing span | Span |
| Stack allocation | Creates a span over stack memory | Span |
| Access elements | Read or write elements by index | span[0] = 10; int x = span[1]; |
| Cannot store in class fields | Span is stack-only and cannot be stored in class fields | Use inside methods only |
Key Takeaways
Use
Span<T> to efficiently access and modify contiguous memory without allocations.Span<T> works on arrays, stack memory, and slices of memory safely.Do not store
Span<T> in class fields because it is a stack-only type.Use
stackalloc to create spans over stack memory for temporary buffers.Modifying a span changes the underlying data directly without copying.