
Often we need to track ranges in arrays. For example, part of an array might be used for a different purpose than other parts. The ArraySegment type is a generic struct that allows us to store information about an array range. It is useful for storing array ranges.
This C# program uses the ArraySegment struct. ArraySegment stores information about ranges.

To start, please notice that the ArraySegment type is generic: it must have a type parameter specified whenever you construct it. The type parameter must be equivalent to the element type of the array. Once you construct the ArraySegment, you can read the Array, Offset, and Count properties from it to retrieve its fields.
In this example, we look at how you can use the original array, the Offset and Count properties, and also how you can loop through the elements specified in the ArraySegment.
Program that uses the ArraySegment type [C#]
using System;
class Program
{
static void Main()
{
// Create an ArraySegment from this array.
int[] array = { 10, 20, 30 };
ArraySegment<int> segment = new ArraySegment<int>(array, 1, 2);
// Write the array.
Console.WriteLine("-- Array --");
int[] original = segment.Array;
foreach (int value in original)
{
Console.WriteLine(value);
}
// Write the offset.
Console.WriteLine("-- Offset --");
Console.WriteLine(segment.Offset);
// Write the count.
Console.WriteLine("-- Count --");
Console.WriteLine(segment.Count);
// Write the elements in the range specified in the ArraySegment.
Console.WriteLine("-- Range --");
for (int i = segment.Offset; i <= segment.Count; i++)
{
Console.WriteLine(segment.Array[i]);
}
}
}
Output
-- Array --
10
20
30
-- Offset --
1
-- Count --
2
-- Range --
20
30
So what are some other usages of the ArraySegment type? Let's say you have a large data array in your program, and want to call methods that act upon different parts of this large array. Copying these parts would cause increased memory usage. Instead, pass an ArraySegment to these methods as an argument; then in these methods, use the ArraySegment to access the large array.

The ArraySegment type is a useful struct in the C# programming language that allows you to specify a range inside a specific array. You can access properties of the ArraySegment to access the original data and also the positional data. In a sense, the ArraySegment can be thought of a facilitation to optimizations that reduce memory copying and heap allocations.
Array Types