preserve dynamic array's old data

  • Thread starter Thread starter watcher
  • Start date Start date
W

watcher

when we redefine an array ,how can we preserve the old data?

string[] a = new string[1];
a[1] = "old data";

when we redefine the array a as following:
a = new string[2];

the data of a[1] was lost

what can i do to prevent it?

thanks a lot
 
Create another variable to hold the new array, and copy the old array's
contents. In VB.NET, you could use Preserve keyword.

string[] a = new string[5];
string[] b = new string[10];

Array.Copy(a, b, 5);
 
watcher said:
when we redefine an array ,how can we preserve the old data?

string[] a = new string[1];
a[1] = "old data";

when we redefine the array a as following:
a = new string[2];

the data of a[1] was lost

what can i do to prevent it?

You would be best doing something like...

string[] b = new string[2];
Array.Copy(a,b,a.Length);
a = b;

It seems to me there is a resize method hiding somewhre in the framework as
well...but I can't recall what it is anylonger.
 
Back
Top