-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?

3
  • Copying your question title into google produces numerous results... have you tried any of them? Commented Jan 6, 2016 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) Commented Jan 6, 2016 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. Commented Jan 6, 2016 at 10:18

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thanks for the fast reaction. But what is the difference between an array and a list?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.