C# Array Segment

ArraySegment is basically a struct which can hold the different segments of an array. The ArraySegment is useful in those cases when you have a large array and on the different parts of this array, calculations are being performed by different methods.

So instead of creating a new array of each calculation, we can pass the segment of the array to methods by using Segment struct. So the methods should only use a part of the array.

Following is the syntax of an array segment in C#

ArraySegment<int>[] segments = new ArraySegment<int>[ArrayCount]
{
    new ArraySegment<int>(array1, offset, number of values),
    new ArraySegment<int>(array2, offset, number of values)
};

In the following example, the array segment is being used to add the segment values. The outer loop is iterating over segment arrays whereas the inner for loop is iterating over segment array elements.

Example

Try It
using System;
 
namespace TLExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array1 = { 10, 20, 30, 40, 50, 60 };
            int[] array2 = { 20, 40, 60, 80, 100, 120, 140, 160, 180, 200 };
 
            ArraySegment<int>[] segments = new ArraySegment<int>[2]
            {
                new ArraySegment<int>(array1, 0, 3),   //Passing 3 values from 0th index - 10, 20, 30
                new ArraySegment<int>(array2, 3, 3)    //Passing 3 values from 3rd index - 80, 100, 120
            };
 
            var sum = AddArraySegments(segments);
            Console.WriteLine("Sum of array segments is: {0}", sum);
        }
 
        static int AddArraySegments(ArraySegment<int>[] ArraySegments)
        {
            int Result = 0;
            foreach (ArraySegment<int> segment in ArraySegments)
            {
                for (int i = segment.Offset; i < segment.Offset + segment.Count; i++)
                {
                    Result += segment.Array[i];
                }
            }
            return Result;
        }
    }
}
Output

Sum of array segments is: 360

Let's learn about the Enumerations in the next section.