Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How list<T> work dynamically although it internally use array(which is fixed)?

I already know about generics and array in c#(i know about dynamic array using pointers in c++), also i know that the arrays are fixed size so we can't change its size after Initialization, we have to allocate a new one then copy......

Lately, I've been using ILspy to see source code of .net assemblies and i found that the List internally rely on a private array but i couldn't figure out how it work, so i wondered, how technically it grows or be resized in memory when I mainpulate it?

like image 717
Ramy Yousef Avatar asked Sep 03 '13 23:09

Ramy Yousef


1 Answers

The List<T> allocates an array T[] of some size and uses it as storage for its items until the array fills up. When a new item needs to be added after that happens, the list allocates a new, larger array and copies all the items from the old array to the new one. The new item can then be added without problem.

As a result of this behavior, appending items to a List is described as an amortized O(1) operation: most appends will take constant time since there is free space in the backing array, but some appends will trigger an array reallocation and take much more time.

The manner of implementation is also apparent from the public interface of List: there is a Capacity property that controls how many items the list can hold without resizing and also a constructor that lets you reserve some specified capacity up front (useful to avoid needless resize operations when you know from beforehand that the list is going to be at least a certain size).

like image 117
Jon Avatar answered Sep 23 '22 04:09

Jon