ZetCode

C# ArraySegment

last modified November 6, 2026

In this article we show how to work with parts of arrays using the ArraySegment<T> struct.

An ArraySegment<T> is a view over a contiguous range of an array. It stores three values: a reference to the array, an offset, and a count. Creating a segment does not copy any elements; reading and writing through the segment accesses the original array.

ArraySegment<T> is older than Span<T>. Spans are faster and work with any contiguous memory, but they are ref struct types: they cannot be stored in fields of classes, in collections, or used across await. A segment is an ordinary struct without these restrictions. It also implements IList<T> and IReadOnlyList<T>, so it works with LINQ and with APIs that take collections.

A view over an array

The constructor takes the array, the offset of the first element, and the number of elements.

Program.cs
int[] vals = [1, 2, 3, 4, 5, 6, 7];

var seg = new ArraySegment<int>(vals, 2, 3);

Console.WriteLine($"Offset: {seg.Offset}, Count: {seg.Count}");
Console.WriteLine($"Segment: [{string.Join(", ", seg)}]");
Console.WriteLine($"Same array: {ReferenceEquals(seg.Array, vals)}");

seg[0] = 30;
vals[4] = 50;

Console.WriteLine($"Segment: [{string.Join(", ", seg)}]");
Console.WriteLine($"Array: [{string.Join(", ", vals)}]");

The segment covers three elements starting at index 2.

var seg = new ArraySegment<int>(vals, 2, 3);

The Offset, Count, and Array properties describe the view. Array returns the original array, not a copy.

seg[0] = 30;
vals[4] = 50;

The indexer is relative to the offset: seg[0] is vals[2]. A change through the segment is visible in the array, and a change in the array is visible through the segment.

$ dotnet run
Offset: 2, Count: 3
Segment: [3, 4, 5]
Same array: True
Segment: [30, 4, 50]
Array: [1, 2, 30, 4, 50, 6, 7]

Slicing

The Slice method creates a smaller segment over the same array. Segments also support the C# index and range operators.

Program.cs
int[] vals = [10, 20, 30, 40, 50, 60, 70, 80];

ArraySegment<int> seg = vals;
ArraySegment<int> mid = seg.Slice(2, 4);
ArraySegment<int> tail = mid.Slice(1);

Console.WriteLine($"mid: [{string.Join(", ", mid)}], offset {mid.Offset}");
Console.WriteLine($"tail: [{string.Join(", ", tail)}], offset {tail.Offset}");

ArraySegment<int> r = mid[1..^1];

Console.WriteLine($"mid[1..^1]: [{string.Join(", ", r)}], offset {r.Offset}");
Console.WriteLine($"mid[^1]: {mid[^1]}");

An array converts implicitly to a segment that covers the whole array.

ArraySegment<int> seg = vals;
ArraySegment<int> mid = seg.Slice(2, 4);
ArraySegment<int> tail = mid.Slice(1);

Slice(2, 4) takes four elements from index 2 of the segment; Slice(1) takes everything from index 1 to the end. The positions are relative to the segment, while Offset always refers to the underlying array.

ArraySegment<int> r = mid[1..^1];

A range expression calls Slice. The 1..^1 range drops the first and the last element of mid; ^1 alone selects the last element.

$ dotnet run
mid: [30, 40, 50, 60], offset 2
tail: [40, 50, 60], offset 3
mid[1..^1]: [40, 50], offset 3
mid[^1]: 60

Bounds checking

A segment checks its own bounds, not the bounds of the array.

Program.cs
int[] vals = [1, 2, 3, 4, 5];
var seg = new ArraySegment<int>(vals, 1, 2);

Console.WriteLine($"seg[1] = {seg[1]}");

try
{
    Console.WriteLine(seg[2]);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

try
{
    var bad = new ArraySegment<int>(vals, 3, 4);
}
catch (ArgumentException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

The array has an element at index 3, but the segment has only two elements, so seg[2] throws ArgumentOutOfRangeException.

var bad = new ArraySegment<int>(vals, 3, 4);

The constructor validates the offset and count: four elements from index 3 do not fit into a five-element array, so it throws ArgumentException.

$ dotnet run
seg[1] = 3
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

Parsing a buffer

Segments are often used to track the filled part of a byte buffer. The example writes length-prefixed records into a buffer and reads them back.

Program.cs
using System.Buffers.Binary;
using System.Text;

byte[] buf = new byte[64];
int len = Write(buf, "falcon");
len += Write(buf.AsSpan(len), "sky");

var data = new ArraySegment<byte>(buf, 0, len);
Console.WriteLine($"Used {data.Count} of {buf.Length} bytes");

while (data.Count > 0)
{
    int n = BinaryPrimitives.ReadInt32LittleEndian(data);
    ArraySegment<byte> payload = data.Slice(4, n);

    Console.WriteLine($"Record of {n} bytes: {Encoding.UTF8.GetString(payload)}");
    data = data.Slice(4 + n);
}

static int Write(Span<byte> dest, string text)
{
    int n = Encoding.UTF8.GetBytes(text, dest[4..]);
    BinaryPrimitives.WriteInt32LittleEndian(dest, n);
    return 4 + n;
}

Each record is a 4-byte little-endian length followed by UTF-8 text. The Write helper takes a Span<byte>, which is the natural type for writing into memory.

var data = new ArraySegment<byte>(buf, 0, len);

The segment covers only the bytes that were written. The rest of the 64-byte buffer is ignored.

int n = BinaryPrimitives.ReadInt32LittleEndian(data);
ArraySegment<byte> payload = data.Slice(4, n);

A segment converts implicitly to ReadOnlySpan<byte>, so it can be passed to BinaryPrimitives and to Encoding.GetString directly. Unlike BitConverter, BinaryPrimitives states the byte order explicitly.

data = data.Slice(4 + n);

After a record is read, the segment moves past it. The loop ends when no bytes are left.

$ dotnet run
Used 17 of 64 bytes
Record of 6 bytes: falcon
Record of 3 bytes: sky

Segments as collections

ArraySegment<T> implements IList<T>, IReadOnlyList<T>, and IEnumerable<T>.

Program.cs
int[] temps = [12, 15, 19, 23, 26, 24, 18, 14];

var summer = new ArraySegment<int>(temps, 3, 3);

Print("summer", summer);
Print("all", temps);

Console.WriteLine($"Max: {summer.Max()}, Avg: {summer.Average():F1}");
IList<int> list = summer;
Console.WriteLine($"Index of 26: {list.IndexOf(26)}");

try
{
    list.Add(30);
}
catch (NotSupportedException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

static void Print(string name, IReadOnlyList<int> items)
{
    Console.WriteLine($"{name}: {items.Count} items, first {items[0]}, last {items[^1]}");
}

The Print method takes an IReadOnlyList<int>. It accepts both the segment and a whole array, so the method does not need separate offset and count parameters.

Console.WriteLine($"Max: {summer.Max()}, Avg: {summer.Average():F1}");

LINQ methods work on segments because they are enumerable.

IList<int> list = summer;
Console.WriteLine($"Index of 26: {list.IndexOf(26)}");

Members such as IndexOf are implemented explicitly, so they are available through the interface. The returned index is relative to the segment.

list.Add(30);

A segment has a fixed size. Add, Insert, and Remove throw NotSupportedException.

$ dotnet run
summer: 3 items, first 23, last 24
all: 8 items, first 12, last 14
Max: 26, Avg: 24.3
Index of 26: 1
NotSupportedException: Specified method is not supported.

Copying a segment

When an independent copy is needed, the segment provides ToArray and CopyTo.

Program.cs
int[] vals = [1, 2, 3, 4, 5, 6];
var seg = new ArraySegment<int>(vals, 1, 3);

int[] copy = seg.ToArray();
copy[0] = 100;

int[] dest = new int[5];
seg.CopyTo(dest, 2);

Console.WriteLine($"vals: [{string.Join(", ", vals)}]");
Console.WriteLine($"copy: [{string.Join(", ", copy)}]");
Console.WriteLine($"dest: [{string.Join(", ", dest)}]");

Span<int> span = seg;
span.Fill(0);
Console.WriteLine($"vals: [{string.Join(", ", vals)}]");

ToArray allocates a new array with the segment's elements; changing the copy does not affect vals.

seg.CopyTo(dest, 2);

CopyTo copies the elements into an existing array, here starting at index 2 of dest.

Span<int> span = seg;
span.Fill(0);

A segment converts implicitly to a span over the same memory. Filling the span with zeros changes the original array.

$ dotnet run
vals: [1, 2, 3, 4, 5, 6]
copy: [100, 3, 4]
dest: [0, 0, 2, 3, 4]
vals: [1, 0, 0, 0, 5, 6]

Chunks in asynchronous code

A span cannot be a parameter of an async method or an element of a list. A segment can, which makes it suitable for splitting an array into chunks that are processed concurrently.

Program.cs
int[] data = Enumerable.Range(1, 10).ToArray();

var chunks = new List<ArraySegment<int>>();
for (int i = 0; i < data.Length; i += 4)
{
    chunks.Add(new ArraySegment<int>(data, i, Math.Min(4, data.Length - i)));
}

int[] sums = await Task.WhenAll(chunks.Select(SumAsync));

Console.WriteLine($"Chunk sums: {string.Join(", ", sums)}");
Console.WriteLine($"Total: {sums.Sum()}");

static async Task<int> SumAsync(ArraySegment<int> chunk)
{
    Console.WriteLine($"offset {chunk.Offset}: [{string.Join(", ", chunk)}]");
    await Task.Delay(100);
    return chunk.Sum();
}

The loop creates segments of at most four elements. The last chunk has only two. Unlike Enumerable.Chunk, which copies the elements into new arrays, the segments share the original array.

int[] sums = await Task.WhenAll(chunks.Select(SumAsync));

Each chunk is passed to an asynchronous method. Task.WhenAll returns the results in the order of the input chunks.

$ dotnet run
offset 0: [1, 2, 3, 4]
offset 4: [5, 6, 7, 8]
offset 8: [9, 10]
Chunk sums: 10, 26, 19
Total: 55

Empty and default segments

A segment created with default has no array, which differs from an empty segment.

Program.cs
ArraySegment<int> def = default;
ArraySegment<int> empty = ArraySegment<int>.Empty;

Console.WriteLine($"default: Array null {def.Array is null}, Count {def.Count}");
Console.WriteLine($"Empty: Array null {empty.Array is null}, Count {empty.Count}");

Console.WriteLine($"Empty items: {empty.Count()}");

try
{
    foreach (int e in def) { }
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

Console.WriteLine($"default as span: {((Span<int>)def).Length}");

Both segments have zero elements. ArraySegment<T>.Empty wraps an empty array, while the default value has a null Array property.

foreach (int e in def) { }

Enumerating a default segment throws InvalidOperationException. Converting it to a span is safe and gives an empty span. Use ArraySegment<T>.Empty when you need an empty segment.

$ dotnet run
default: Array null True, Count 0
Empty: Array null False, Count 0
Empty items: 0
InvalidOperationException: The underlying array is null.
default as span: 0

Source

ArraySegment<T> struct

In this article we have worked with parts of arrays using ArraySegment<T>.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.