Home
Map
ArraySegment ExampleUse ArraySegment to store information about ranges in arrays, with offsets and counts.
C#
This page was last reviewed on May 13, 2023.
ArraySegment. Often we need to track ranges in C# arrays. For example, part of an array might be used for a different purpose than other parts.
ArraySegment is a generic struct that stores information about an array range. We can create ArraySegments and pass them to methods to operate on parts of arrays.
Generic
struct
Array
An example. ArraySegment must have a type parameter—this must match the array type. Once you construct the ArraySegment, you can read the Array, Offset, and Count to retrieve its fields.
Info We use the original array, the Offset and Count properties, and loop through the elements specified in the ArraySegment.
Property
Argument 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.
using System; // 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]); }
-- Array -- 10 20 30 -- Offset -- 1 -- Count -- 2 -- Range -- 20 30
Discussion. Let's say you have a large data array, and want to call methods that act upon different parts of this large array. Copying these parts would cause increased memory usage.
So Pass an ArraySegment to these methods as an argument. In these methods, use the ArraySegment to access the large array.
A summary. ArraySegment 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 13, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.