How does the <T> list work dynamically, although it internally uses an array (which is fixed)?
I already know about generics and an array in C # (I know about a dynamic array using pointers in C ++), I also know that arrays are fixed size, so we cannot resize it after initialization, we must select a new one then copy ......
Recently, I have been using ILspy to view the source code for .net collections, and I found that List relies internally on a private array, but I couldn’t figure out how it works, so I wondered how technically it grows or resize in memory when will i do this?
List<T> allocates an array of T[] some size and uses it as storage for its elements until the array is full. When after that you need to add a new element, the list selects a new larger array and copies all the elements from the old array to the new one. A new item can be added without problems.
As a result of this behavior, the added elements to the List are described as amortized O (1): most additives will take a constant time because there is free space in the backup array, but some additions will cause the array to be redistributed and take much longer.
The implementation method also appears in the open List interface: there is the Capacity property, which controls the number of elements that the list can store without resizing, as well as a constructor that allows you to reserve a certain capacity up (it is useful to avoid unnecessary resizing operations when you know in advance that the list will be at least a certain size).