Span/ReadOnlySpan fundamentals (C# 6 emulation)
Emulate Span/ReadOnlySpan with ArraySegment : create views over arrays, slice with offset/length, and process data without copying.
Why slices matter
Aim: Work with slices without extra allocations.
- Use ArraySegment<T> as a view
- Slice by offset and count
- Write methods that accept ArraySegment<T>
- Keep operations simple and safe
Zero-copy view
ArraySegment<T> is a zero-copy view over part of an array. Pass it to methods to avoid slicing copies.
using System;
public class Program
{
static int Sum(ArraySegment<int> seg)
{
int acc = 0;
int end = seg.Offset + seg.Count;
for (int i = seg.Offset; i < end; i++) acc += seg.Array[i];
return acc;
}
public static void Main(string[] args)
{
int[] data = new int[] { 2, 4, 6, 8, 10 };
ArraySegment<int> middle3 = new ArraySegment<int>(data, 1, 3); // 4,6,8
Console.WriteLine("Sum = " + Sum(middle3)); // 18
}
}
All lessons in this course
- Span/ReadOnlySpan fundamentals (C# 6 emulation)
- Memory/ReadOnlyMemory emulation: zero-copy windows
- String-as-Span APIs (C# 6 emulation)