It looks like your indexer is off by one:
int idx = this._offset + index - 1;
If offset is 1 (starting from the second element of the array) and index is zero (returning the first element of the section), you will return the first element of the array, not the second.
Good catch Richard!
It is more of a container class to allow passing Lists of ArraySegments to a method. For example, the Socket class now allows passing ArraySegments so you can get scatter/gather semantics. You could not pass parcial buffers without something like ArraySegment and would need to copy to buffer of exact size. It is probably most useful for bytes, but it did not really cost anything to make it generic - so I guess that why it is generic.
However, I had the exact same problem... and had to roll my own DelimitedArray<T>, which looks very much like Wim's.
How is this faster than the base .NET implementation? Sure, it is convenient to use, but the very first issue I see is you declared this as a "class" as opposed to .NET's implementation which declares it as a "struct."
I doubt there may be bug in you ArraySegment.
If the size of the intenal array is 10 and you create a ArraySegment object with Count 12, what may happen?
Thanks, a had same problem
Shouldn't this class Implement IEnumerable?
Also, it would be quicker if you don't check to make sure the index into the array is valid (where you throw the exception) as the wrapped array will be doing this check for you a second time.
You have a tough crowd you are trying to please, judging from some of the comments.
I too think that there are already thousands of vocabulary words to remember when dealing with dot net and C#. A program has to learn more new words during their education than a foreign language student. One has to ask if it was really required to add another nonsense word in order to add this functionality.
I agree with you. It is complication that is not worth it.
By changing T into IEnumerable<T> and changing this._array[idx] into this._array.ElementAt(idx) you can actually pass almost any list or array into it and still get your segment/part/delimited array of elements.
I had to add The non-generic GetEnumerator as well to get this to work:
Awesome article, you really nailed it.
let's say you want to pass a function multiple arrays and offsets and lengths... look for example socket.BeginSend: you don't want to copy all the values to a new array because it spends time and memory, therefore, you send List of ArraySegments.
Looks like the finally fixed it in .NET 4.5!