We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

ecavazos on 01/18/08


Tagged

array add append copyto


Versions (?)


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.