What is Span in C#: Explanation and Examples
Span<T> in C# is a special type that lets you work with a continuous region of memory safely and efficiently without copying data. It acts like a window over arrays or other memory blocks, allowing fast access and manipulation of data slices.How It Works
Span<T> works like a lightweight view or window over a block of memory, such as an array or part of an array. Imagine you have a long ribbon (an array), and you want to look at or change just a small section of it without cutting or copying the ribbon. Span<T> lets you do exactly that by pointing to a part of the ribbon.
It does this without creating a new array or copying data, which makes it very fast and memory-friendly. Because it only points to existing memory, it is a stack-only type, meaning it cannot be stored on the heap or used across async calls, which helps keep it safe and efficient.
Example
This example shows how to create a Span<int> from an array and modify a part of it without copying the array.
using System; class Program { static void Main() { int[] numbers = { 10, 20, 30, 40, 50 }; Span<int> slice = numbers.AsSpan(1, 3); // points to elements 20, 30, 40 // Modify the slice for (int i = 0; i < slice.Length; i++) { slice[i] += 5; } // Print the original array to see changes foreach (var num in numbers) { Console.Write(num + " "); } } }
When to Use
Use Span<T> when you need to work with parts of arrays or memory buffers efficiently without copying data. It is great for performance-critical code like parsing, processing large data streams, or manipulating slices of arrays.
For example, if you are reading data from a file or network and want to process chunks without creating new arrays each time, Span<T> helps reduce memory use and speeds up your program.
Key Points
Span<T>is a stack-only type that points to continuous memory.- It allows safe, fast access to slices of arrays or buffers without copying.
- Cannot be stored on the heap or used across async/await boundaries.
- Useful for high-performance scenarios like parsing and data processing.
Key Takeaways
Span<T> provides a fast, memory-efficient way to work with parts of arrays or memory.