Copying an Array


A typical thing to do while working with arrays is to expand the array. You learned earlier that array sizes are immutable. So to expand (or shrink) the array you need to create a brand-new array with the new dimensions, then copy the items from the previous array onto the new one.

To copy the elements from one array into another:

  1. Type System.Array.Copy .

  2. Type an open parenthesis ( .

  3. If the first array is called src and the second array is called dest , type src,srcstartindex,dest,deststartindex, src.Length .

  4. Type a close parenthesis ) .

  5. Type a semicolon ; ( Figure 9.48 ).

    Figure 9.48 This code creates a new array and copies the elements from the old array into the new array. The last parameter in the Copy function is the number of elements to copy. It's not very forgiving concerning this parameter. If there's not enough room, it will give you an exception.
     void Task() {   string[] moviesILike = new string[]   {"Joe vs. the Volcano", "Pink Panther", "LOTR"};   string[] newMovies = new string[4];  Array.Copy  (moviesILike,0,newMovies,0,moviesI Like.Length);   newMovies[3] = "The Princess Bride";   moviesILike = newMovies; } 

graphics/tick.gif Tips

  • Array.Copy lets you specify the starting index in the source array from where you wish to begin copying, and the starting index in the destination to where you wish to copy, as well as the number of items that you wish to copy.

  • To insert an item within the array, create a new array. Then copy the first half of the source onto the first half of the destination array. Finally, copy the rest of the source array onto the last portion of the array, leaving a place empty for the new item ( Figure 9.49 ).

    Figure 9.49 This code inserts Princess Bride as the second element in the array. To do that it needs to create a new array, then copy the first half of the old array, set the new element, then copy the remainder of the array.
     void Task() {    string[] moviesILike = new string[] {    "Joe vs. the Volcano", "Pink Panther", "LOTR"};    string[] newMovies = new string[4];  Array.Copy  (moviesILike,0,newMovies,0,1);    newMovies[1] = "The Princess Bride";  Array.Copy  (moviesILike,1,              newMovies,2,              moviesILike.Length-1);    moviesILike = newMovies; } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net