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?
The ArraySegment<T> structure is useful whenever the elements of an array will be manipulated in distinct segments.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With