Arrays
1. Does c# Array size can be changed at runtime? For e.g. I start with a 10 member array of inegers and then later on at runtime, if I insert a 11th integer - will it be possible?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jul 29, 2012, 5:00 AM EDT
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Array.Resize(ref myArray, 11);
myArray[10] = 11;
However, this actually creates a new array and copies the elements of the old array to the new one. It doesn't change the size of the original array which is technically impossible.
If you need a resizeable collection, then it's generally better to use a List
C Kelvin9 reputationPosted Jul 29, 2012, 5:25 AM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 29, 2012, 5:32 AM EDT
Internally, the ArrayList uses an array of objects as its backing store.
If I remember correctly, the initial size of the internal array is 4 but when a fifth element is added, this is doubled to 8 and continues to be doubled as needed.
However, the difference between this and Array.Resize is that you don't have to think about it - it's done automatically for you in the background.
List
In the case of value types (int, double, bool etc), this means that 'boxing' - a relatively slow operation - is not needed and when retrieving an element from the collection you don't have to cast it to its actual type.
C Kelvin9 reputationPosted Jul 29, 2012, 5:44 AM EDT