C# Span Slice — Complete Guide
In this tutorial, you'll learn about C# Span Slice. We cover key concepts, practical examples, and best practices.
You need to work with a portion of an array — parsing a buffer, processing a segment of data. You create a new array with Array.Copy or use Skip/Take which allocate. Span<T>.Slice creates a view into the existing array with zero allocation.
Wrong
byte[] header = new byte[4];
Array.Copy(data, 0, header, 0, 4); // Allocates new array
// or
byte[] header = data.Take(4).ToArray(); // LINQ allocation
Output: New byte[4] allocated. Memory and GC pressure for the copy.
Right
Span<byte> dataSpan = data;
Span<byte> header = dataSpan.Slice(0, 4);
// Use header directly — no allocation, no copy
Output: header is a view into the original data array. No allocation. The same memory is referenced.
Slice with start only:
Span<byte> remainder = dataSpan.Slice(4); // From index 4 to end
Span<T> supports all common operations:
Span<int> numbers = stackalloc int[] { 1, 2, 3, 4, 5 };
Span<int> firstThree = numbers[..3]; // Slice syntax
Span<int> lastTwo = numbers[^2..]; // From 2nd-to-last
Prevention
- Use
Sliceinstead ofSkip/Take/Array.Copywhen working with array segments. - Use
Span<T>for stack-allocated buffers and zero-allocation slicing. - Use
ReadOnlySpan<T>when you do not need to modify the data. - Use range syntax
[start..end]as shorthand forSlice. - Use
Memory<T>for heap-allocated async operations (stored on heap). - Avoid
Span<T>in async methods — spans are stack-only.
Common Mistakes with span slice
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Span<T>.Slice is used in Durga Antivirus Pro to parse file headers without copying buffers. For more C# memory optimization, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro