0

How can I add a new line to an array? The array is currently empty.

I tried this but it didn't work

string[] testarray;
testarray[0] = "Lorem ipsum dolor sit amet";
testarray[1] = "example text 1";

int i = testarray.Length;
i++;
testarray[i] = "example text 2";

Thanks

0

1 Answer 1

1

You can try initializing the array with required items:

 string[] testarray = new string[] {
   "Lorem ipsum dolor sit amet",
   "example text 1",
   "example text 2",  
 };

Or use List<string> and Add items in dynamic:

 List<string> testArray = new List<string>();

 testArray.Add("Lorem ipsum dolor sit amet"); 
 testArray.Add("example text 1");

 ...

 testArray.Add("example text 2");

If you insist on array changing its length in dynamic, you have to put something like this (note, array is not the collection type designed to change its length):

 string[] testarray = new string[0];

 ...

 // recreates testarray with longer Length
 Array.Resize(ref testarray, testarray.Length + 1);
 // put the value at the last cell
 testarray[testarray.Length - 1] = "Lorem ipsum dolor sit amet";

 ...
 
 Array.Resize(ref testarray, testarray.Length + 1);

 testarray[testarray.Length - 1] = "example text 1";

 ...
 
 Array.Resize(ref testarray, testarray.Length + 1);

 testarray[testarray.Length - 1] = "example text 2";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this worked for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.