How to generate a variable-length array in C#?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I intend to generate a variable-length array, similar to link lists in plain C. For example, I define the following array

int [] a

Initially I assign 5 elements to the array as

a = new int[5]
for( k = 0; k < 5; k++
a[k] = k

Then I want to expand the array to 7 elements without discarding the original 5 elements. How to do
 
I intend to generate a variable-length array, similar to link lists in
plain C. For example, I define the following array:
Then I want to expand the array to 7 elements without discarding the
original 5 elements. How to do?

Create a new array with the new size and copy over the existing elements.
Then replace the existing array with the new one.

Something like:

Int32[] b = new Int32[7];
Array.Copy(a, 0, b, 0, 5);
a = b;

You might want to look at the ArrayList class too.
 
Back
Top