Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T>.AddRange / InsertRange creating temporary array

Tags:

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.

like image 964
CSharpie Avatar asked Apr 13 '16 14:04

CSharpie


1 Answers

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().

like image 175
usr Avatar answered Sep 28 '22 01:09

usr