Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy one string array to another

Tags:

How can I copy a string[] from another string[]?

Suppose I have string[] args. How can I copy it to another array string[] args1?

like image 421
Arunachalam Avatar asked May 20 '09 06:05

Arunachalam


1 Answers

  • To create a completely new array with the same contents (as a shallow copy): call Array.Clone and just cast the result.
  • To copy a portion of a string array into another string array: call Array.Copy or Array.CopyTo

For example:

using System;  class Test {     static void Main(string[] args)     {         // Clone the whole array         string[] args2 = (string[]) args.Clone();          // Copy the five elements with indexes 2-6         // from args into args3, stating from         // index 2 of args3.         string[] args3 = new string[5];         Array.Copy(args, 2, args3, 0, 5);          // Copy whole of args into args4, starting from         // index 2 (of args4)         string[] args4 = new string[args.Length+2];         args.CopyTo(args4, 2);     } } 

Assuming we start off with args = { "a", "b", "c", "d", "e", "f", "g", "h" } the results are:

args2 = { "a", "b", "c", "d", "e", "f", "g", "h" } args3 = { "c", "d", "e", "f", "g" } args4 = { null, null, "a", "b", "c", "d", "e", "f", "g", "h" }  
like image 71
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet