Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of the ArraySegment<T> class?

Tags:

arrays

c#

.net

I just came across the ArraySegment<byte> type while subclassing the MessageEncoder class.

I now understand that it's a segment of a given array, takes an offset, is not enumerable, and does not have an indexer, but I still fail to understand its usage. Can someone please explain with an example?

like image 437
stackoverflowuser Avatar asked Jan 05 '11 01:01

stackoverflowuser


People also ask

Why use ArraySegment?

The ArraySegment<T> structure is useful whenever the elements of an array will be manipulated in distinct segments.

How do you slice an array in C#?

Using the Copy() Method to Slice Array And then we call the Copy() method which takes a source array, starting index, destination array, starting destination index (zero because we're copying to a new array), and a number of elements we want to slice. As we see, this method works the same as the LINQ one.


1 Answers

ArraySegment<T> has become a lot more useful in .NET 4.5+ and .NET Core as it now implements:

  • IList<T>
  • ICollection<T>
  • IEnumerable<T>
  • IEnumerable
  • IReadOnlyList<T>
  • IReadOnlyCollection<T>

as opposed to the .NET 4 version which implemented no interfaces whatsoever.

The class is now able to take part in the wonderful world of LINQ so we can do the usual LINQ things like query the contents, reverse the contents without affecting the original array, get the first item, and so on:

var array = new byte[] { 5, 8, 9, 20, 70, 44, 2, 4 }; array.Dump(); var segment = new ArraySegment<byte>(array, 2, 3); segment.Dump(); // output: 9, 20, 70 segment.Reverse().Dump(); // output 70, 20, 9 segment.Any(s => s == 99).Dump(); // output false segment.First().Dump(); // output 9 array.Dump(); // no change 
like image 187
Stephen Kennedy Avatar answered Oct 05 '22 10:10

Stephen Kennedy