Reputation: 9467
While looking at the Implementation of List.AddRange i found something odd i do not understand. Sourcecode, see line 727 (AddRange calls InsertRange)
T[] itemsToInsert = new T[count];
c.CopyTo(itemsToInsert, 0);
itemsToInsert.CopyTo(_items, index);
Why doest it Copy the collection into a "temp-array" (itemsToInsert) first and then copies the temp array into the actual _items-array? Is there any reason behind this, or is this just some leftover from copying ArrayList's source, because the same thing happens there.
Upvotes: 5
Views: 515
Reputation: 171178
My guess is that this is to hide the existence of the internal backing array. There is no way to obtain a reference to that array which is intentional. The List
class does not even promise that there is such an array. (Of course, for performance and for compatibility reasons it will always be implemented with an array.)
Someone could pass in a crafted ICollection<T>
that remembers the array that it is passed. Now callers can mess with the internal array of List
and start depending on List
internals.
Contrast this with MemoryStream
which has a documented way to access the internal buffer (and shoot yourself with it): GetBuffer()
.
Upvotes: 4