I just came across the ArraySegment
type while subclassing the MessageEncoder
class.
I now understand that it\'s a segment of a
- Buffer partioning for IO classes - Use the same buffer for simultaneous read and write operations and have a single structure you can pass around the describes your entire operation.
- Set Functions - Mathematically speaking you can represent any contiguous subsets using this new structure. That basically means you can create partitions of the array, but you can't represent say all odds and all evens. Note that the phone teaser proposed by The1 could have been elegantly solved using ArraySegment partitioning and a tree structure. The final numbers could have been written out by traversing the tree depth first. This would have been an ideal scenario in terms of memory and speed I believe.
- Multithreading - You can now spawn multiple threads to operate over the same data source while using segmented arrays as the control gate. Loops that use discrete calculations can now be farmed out quite easily, something that the latest C++ compilers are starting to do as a code optimization step.
- UI Segmentation - Constrain your UI displays using segmented structures. You can now store structures representing pages of data that can quickly be applied to the display functions. Single contiguous arrays can be used in order to display discrete views, or even hierarchical structures such as the nodes in a TreeView by segmenting a linear data store into node collection segments.
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.
using System;
class Program
{
static void Main()
{
// Create an ArraySegment from this array.
int[] array = { 10, 20, 30 };
ArraySegment segment = new ArraySegment(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+segment.Offset; i++)
{
Console.WriteLine(segment.Array[i]);
}
}
}
ArraySegment Structure - what were they thinking?