Posted By

ecavazos on 01/18/08


Tagged

array add append copyto


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

umang_nine
vali29
orhanveli


Add Item to Array


 / Published in: C#
 

There may be a simpler way to do this but this is the only way I could find to solve this problem. There is no Add method for basic arrays.

  1. // Add an item to the end of an existing array
  2. string[] ar1 = new string[] {"I", "Like", "To"}
  3.  
  4. // create a temporary array with an extra slot
  5. // at the end
  6. string[] ar2 = new string[ar1.Length + 1];
  7.  
  8. // add the contents of the ar1 to ar2
  9. // at position 0
  10. ar1.CopyTo(ar2, 0);
  11.  
  12. // add the desired value
  13. ar2.SetValue("Code.", ar1.Length);
  14.  
  15. // overwrite ar1 with ar2 and voila!
  16. // the contents of ar1 should now be {"I", "Like", "To", "Code."}
  17. ar1 = ar2;

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: tsounth on January 19, 2008

Very nice!

Posted By: ptoutant on June 20, 2008

Array.Resize(ref ar1, ar1.Length + 1); Array.Copy(new object[] { "Code." }, 0, ar1, ar1.Length - 1, 1);

You need to login to post a comment.