-3

i want to simply add a string to an array, like this:

string[] arrayName = new string[0];
        arrayName.Add("raptor");

But this doesn't work, can someone help me?

Bv dL
  • 61
  • 1
  • 6
  • Copying your question title into google produces [numerous results](https://www.google.co.uk/search?q=c%23+adding+a+string+to+an+array&ie=utf-8&oe=utf-8&gws_rd=cr&ei=G-aMVoH9NYHJaOu3oeAB)... have you tried any of them? – Sayse Jan 06 '16 at 10:02
  • arrays are immutable. when you create array of size 0 you cant change it. the only way is to recreate a new array with bigger size. (which list does) – M.kazem Akhgary Jan 06 '16 at 10:06
  • Another way to do this (although I *definitely* recommend the use of generic collections) would be to resize your array, that's if you wanted to stick with arrays. `Array.Resize(ref arrayName, 1); arrayName[0] = "raptor";` You could wrap that up in your own `Add` method if you must. –  Jan 06 '16 at 10:18

1 Answers1

2

You should use a generic List(Of T).

List<string> myStrings = new List<string>();
myStrings.Add("raptor");

and if you really want an array:

string[] myStringArray = myStrings.ToArray();
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • Wow, thanks for the fast reaction. But what is the difference between an array and a list? – Bv dL Jan 06 '16 at 10:02
  • @BvdL Generally speaking, a list is a collection that you can easily add/remove items to/from. An array usually has a fixed size, which is not that convenient to modify. – Cheng Chen Jan 06 '16 at 10:04