redimension array

  • Thread starter Thread starter y
  • Start date Start date
Y

y

Hi,

I have an array with 2 elements and I would like to keep
the elements but redimension the array so that I can add
another value.

How do I do this.

I have tried this but, i think I have screwy logic.

Thanks


intRedimArray = arr_Selected.Length;
object tmp_arr = arr_Selected.Clone();
arr_Selected (string [])tmp_arr;
arr_Selected = new string[intRedimArray];

arr_Selected[intArrayCounter-1] = strToAdd;
tmp_arr= null;

the program will keep showing 1.
MessageBox.Show(arr_Selected.Length.ToString());


Thanks for your help,

y
 
intRedimArray = arr_Selected.Length;
object tmp_arr = arr_Selected.Clone();
arr_Selected (string [])tmp_arr;
arr_Selected = new string[intRedimArray];

arr_Selected[intArrayCounter-1] = strToAdd;
tmp_arr= null;

the program will keep showing 1.
MessageBox.Show(arr_Selected.Length.ToString());

This won't work because the array size for 'new string[intRedimArray]'
should be a compile time constant. You can use Array.CreateInstance instead.
 
y,
To redimension an array you need to create a new array, copy the existing
elements to the new array, start using the new array.

Something like:
string[] list;

int newLength = list.Length + 5;

string[] temp = new string[newLength];
list.CopyTo(temp, 0);

list = temp;

Note, if you are decreasing the size of the array, you can use Array.Copy
instead of CopyTo.

Array.Copy(list, 0, temp, 0, newLength);

Actually Array.Copy works for either increasing or decreasing the array. As
long as you don't try to copy more elements than what is in the source array
or the destination array.

Hope this helps
Jay
 
This won't work because the array size for 'new string[intRedimArray]'
should be a compile time constant.

I'm affraid this statement is not quite correct....
 
Val Savvateev said:
This won't work because the array size for 'new string[intRedimArray]'
should be a compile time constant.

I'm affraid this statement is not quite correct....

I'm affraid you're right... my C++ background is showing :)
 
Back
Top