change array size
Is it possible to change an array size after declaration? If not, is there any alternative to arrays?
I do not want to create an array with a size of 1000, but I do not know the size of the array when I’m creating it.
16 Answers 16
You can use Array.Resize() , documented in MSDN.
But yeah, I agree with Corey, if you need a dynamically sized data structure, we have List s for that.
Important: Array.Resize() doesn’t resize the array (the method name is misleading), it creates a new array and only replaces the reference you passed to the method.
No, try using a strongly typed List instead.
Instead of using
You could do this:
Lists use arrays to store the data so you get the speed benefit of arrays with the convenience of a LinkedList by being able to add and remove items without worrying about having to manually change its size.
This doesn’t mean an array’s size (in this instance, a List ) isn’t changed though — hence the emphasis on the word manually.
As soon as your array hits its predefined size, the JIT will allocate a new array on the heap that is twice the size and copy your existing array across.
Yes, it is possible to resize an array. For example:
If you create an array with CreateInstance() method, the Resize() method is not working. For example:
The array size is not dynamic, even we can resize it. If you want a dynamic array, I think we can use generic List instead.
You can use Array.Resize() in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. (So you will need the memory available for both arrays as this probably uses Array.Copy under the covers)
![]()
In C#, arrays cannot be resized dynamically.
One approach is to use System.Collections.ArrayList instead of a native array .
Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array.
The generic function resizeArray (below) can be used to do that.
![]()
Used this approach for array of bytes:
Whenever required (Need to provide original length for extending):
Typed List Method
Use a List<T> instead. For instance, instead of an array of ints
In C#, Array.Resize is the simplest method to resize any array to new size, e.g.:
Here, i want to resize the array size of LinkButton array:
<LinkButton> = specifies the array type
ref area = ref is a keyword and ‘area’ is the array name
size = new size array
![]()
If you really need to get it back into an array I find it easiest to convert the array to a list , expand the list then convert it back to an array .
Use a List (where T is any type or Object) when you want to add/remove data, since resizing arrays is expensive. You can read more about Arrays considered somewhat harmful whereas a List can be added to New records can be appended to the end. It adjusts its size as needed.
A List can be initalized in following ways
Using collection initializer.
Using var keyword with collection initializer.
Using new array as parameter.
Using capacity in constructor and assign.
Using Add method for each element.
Thus for an Object List you can allocate and assign the properties of objects inline with the List initialization. Object initializers and collection initializers share similar syntax.
Как изменить размер массива с
Все массивы в C# построены на основе класса Array из пространства имен System. Этот класс определяет ряд свойств и методов, которые мы можем использовать при работе с массивами. Основные свойства и методы:
Свойство Length возвращает длину массива
Свойство Rank возвращает размерность массива
int BinarySearch (Array array, object? value) выполняет бинарный поиск в отсортированном массиве и возвращает индекс найденного элемента
void Clear (Array array) очищает массив, устанавливая для всех его элементов значение по умолчанию
void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) копирует из массива sourceArray начиная с индекс sourceIndex length элементов в массив destinationArray начиная с индекса destinationIndex
bool Exists<T> (T[] array, Predicate<T> match) проверяет, содержит ли массив array элементы, которые удовлеворяют условию делегата match
void Fill<T> (T[] array, T value) заполняет массив array значением value
T? Find<T> (T[] array, Predicate<T> match) находит первый элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
T? FindLast<T> (T[] array, Predicate<T> match) находит последний элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
int FindIndex<T> (T[] array, Predicate<T> match) возвращает индекс первого вхождения элемента, который удовлеворяет определенному условию делегата match
int FindLastIndex<T> (T[] array, Predicate<T> match) возвращает индекс последнего вхождения элемента, который удовлеворяет определенному условию
T[] FindAll<T> (T[] array, Predicate<T> match) возвращает все элементы в виде массива, которые удовлеворяет определенному условию из делегата match
int IndexOf (Array array, object? value) возвращает индекс первого вхождения элемента в массив
int LastIndexOf (Array array, object? value) возвращает индекс последнего вхождения элемента в массив
void Resize<T> (ref T[]? array, int newSize) изменяет размер одномерного массива
void Reverse (Array array) располагает элементы массива в обратном порядке
void Sort (Array array) сортирует элементы одномерного массива
Разберем самые используемые методы.
Поиск индекса элемента
Если элемент не найден в массиве, то методы возвращают -1.
Поиск элемента по условию
Изменение порядка элементов массива
Например, изменим порядок элементов:
Также можно изменить порядок только части элементов:
В данном случае изменяем порядок только 3 элементов начиная c индекса 1.
Изменение размера массива
Для изменения размера массива применяется метод Resize. Его первый параметр — изменяемый массив, а второй параметр — количество элементов, которые должны быть в массиве. Если второй параметр меньше длины массива, то массив усекается. Если значение параметра, наоборот, больше, то массив дополняется дополнительными элементами, которые имеют значение по умолчанию. Причем первый параметр передается по ссылке:
Копирование массива
Метод Copy копирует часть одного массива в другой:
В данном случае копируем 3 элемента из массива people начиная c индекса 1 и вставляем их в массив employees начиная с индекса 0.
Сортировка массива
Отсортируем массив с помощью метода Sort() :
Этот метод имеет много перегрузок. Например, одна из версий позволяет отсортировать только часть массива:
Изменение размера массива
А нужно увеличить +1 элемент, не потеряв предыдущих данных ?
Изменение размера массива
Как без использования функций изменить размер массива? int x=10; int m1; int m2; int m3; iny.
Изменение размера массива
Допустим в main-е я объявил указатель определенного типа и создал переменную int size, затем адрес.
Изменение размера массива
Задача такая: нужно добавить в массив элемент так что бы он стоял в начале массива или.
Изменение размера массива
Здравствуйте. Я хочу написать массив в который записываются введенные данные. Массив должен.
C# Array.Resize Examples
It then copies existing element values to the new array. This logic is needed when an array's size is inadequate. We show how Resize reallocates and copies elements.


Example. This first example uses Array.Resize to replace a large array with a smaller one. This is useful if we have a large array of data, and want to only keep the first number of bytes or elements.
Here: Array.Resize changes an array with four elements to one with two elements.

Internals. Internally, the single call to Array.Resize above runs through an algorithm that determines that the array needs to be smaller. So it copies the referenced array to a new array, and then changes the reference.
So: Array.Resize is a misnomer. It does not resize the array. It replaces the array with a new one of a different size.
Example 2. Next, we replace an array with a larger one with Array.Resize. This can be useful for certain data structures, such as those that must accommodate more data but have minimal memory footprint.
Note: I have used this in implementing hash table buckets. Array.Resize is helpful in optimization tasks.
Caution: If we omit the Array.Resize call, we will get an IndexOutOfRangeException. This exception should be avoided.

Copy. When doing performance analysis, using IL Disassembler to see what the Framework methods do is important. The Array.Resize method always copies the array, unless it throws an exception. Most calls will internally invoke Array.Copy.
Performance. Copying your array completely when resizing it is wasteful in many situations. For these cases, use List. But sometimes Array.Resize can lead to better performance. Arrays boost memory efficiency and lookup speed.
Note: I have used this method to improve performance in a custom hashtable, which could use arrays of buckets and not Lists.
And: This reduced memory usage. In the end, it significantly enhanced performance.