Array reallocation question

  • Thread starter Thread starter Oleg Subachev
  • Start date Start date
O

Oleg Subachev

Are existing elements in the array preserved when array is reallocated ?

int[] A = new int[1];
A[0] = 1;
A = new int[ A.Length + 1 ];
A[1] = 2;

Will A[0] be 1 at this point ?

Oleg Subachev
 
No, they aren't. the new array is wiped to 0s. You could, however, create
the new array in a second variable, then oldArray.CopyTo(newArray, 0) to get
the values from the old array to the new array.

However, if you are going to be doing this often, then maybe you are using
the wrong object structure? Maybe use a list or collection wrapper?

Marc
 
Back
Top