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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
C KelvinPosted Jul 29, 2012, 9:44 AM
VulpesPosted Jul 29, 2012, 9:32 AM
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 KelvinPosted Jul 29, 2012, 9:25 AM
VulpesPosted Jul 29, 2012, 9:00 AM
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