Posted by: Cirilo Meggiolaro | 11/21/2008

Tip of the day #38 – Array segments

The generic structure ArraySegment<T> provides a way to create a sub array from a one-dimensional array based on an offset and a counter.

The ArraySegment will be instantiated with the specific sequence of <T> type but will not change any value or size on the base array.

Properties

Three read-only properties are available for the ArraySegment object:

Offset: Gets the position from the first element based on the original Array.

Count: Gets the number of items to retrieve. In fact is the ArraySegment size.

Array: Gets an array of <T> type with only the items from the range defined by the Offset and Count Properties.

Exceptions:

Some rules apply when you create an ArraySegment object:

1. The original array must be zero-based index;

2. The original array must be one-dimensional;

3. If the Offset or Count values are less than zero, an ArgumentOutOfRangeException will be thrown;

4. If the original array is not a valid instance, an ArgumentNullException will be thrown;

5. If the original array does not contain items within the Offset or Count range or if any of these properties are out of the array boundaries, an ArgumentException will be thrown.

How to…

Let’s create an array of integers.

int[] myArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

To create a sequence of part of the array, let’s create an instance of the ArraySegment structure. You can use one of the constructor overloads available to create the segment.

The following code passes as parameter the base array, the start index (offset) and the number of items to store (counter);

ArraySegment<int> myArraySegment = new ArraySegment<int>(myArray, 5, 4);

The following code loops through the items stored in the ArraySegment structure:

for (int i = myArraySegment.Offset; i < myArraySegment.Offset + myArraySegment.Count; i++)
{
    Console.WriteLine(myArraySegment.Array[i]);
}

// Output: 5 6 7 8

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: