Add value

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

How can i add values to a string array?

string[] arr = {"a","b","c"};

string s = "X";

I'd like to add x to the front of the array so the array would look like
this.
{"X","a","b","c"};

I tried arr[] +=s; but it didnt work
what did i do wrong?
 
Aaron said:
How can i add values to a string array?

string[] arr = {"a","b","c"};

string s = "X";

I'd like to add x to the front of the array so the array would look like
this.
{"X","a","b","c"};

I tried arr[] +=s; but it didnt work
what did i do wrong?

An array has a fixed length, once defined (in your case: 3). It is not
possible to
add elements anywhere.

However, there is also an ArrayList, which DOES support "Add" and "Insert"
methods (only drawback: it stores anonymous "object's").
If I read the docs correctly, you can create a new ArrayList with your array
as a parameter. It is also possible to convert the ArrayList to a "real"
array
with the "ToArray" method.

Hans Kesting
 
You have to make a new array in that case, the size of an array is fixed
on creation.

string arr2 = new string[arr.Length + 1];
arr2[0] = "X";

for(int i = 0; i < arr.Length; i++)
{
arr2[i+1] = arr;
}
 
Back
Top