C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Example: We use the original array, the Offset and Count properties, and loop through the elements specified in the ArraySegment.
PropertyArgument 1: The first argument to ArraySegment is the array—this must have the same type of elements as the ArraySegment.
Argument 2: This is the offset into the array—to start at the second element, pass the index 1.
Argument 3: This is the count of elements (not the end index) that is being referred to by the ArraySegment.
C# program that uses ArraySegment
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
Instead: Pass an ArraySegment to these methods as an argument. In these methods, use the ArraySegment to access the large array.
However: ArraySegment might be more standardized, and could be easier for other developers to maintain and understand.