Add Item to Array


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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

You need to login to post a comment.