Mohamed Mohamed
Mohamed Mohamed

Reputation: 1

how can i to add items to an already created Array

i have string array as the following string[] strArray = new string[] { "1", "2", "3", "5", "6" }; the question is how can i add item to this created Array at specific position to be like { "1", "2", "3" , "4" , "5", "6" } i need some thing can append value at specific index and keep the old values

Upvotes: 0

Views: 72

Answers (2)

John Castleman
John Castleman

Reputation: 1561

Arrays are immutable, but Lists are not:

var list = strArray.ToList();
list.Add("6")
strArray = list.ToArray();

Or, at a specific index:

var list = strArray.ToList();
list.Insert(3, "4");
strArray = list.ToArray();

Upvotes: 0

Dennis
Dennis

Reputation: 37780

You can't do this, since arrays have fixed length after creation. Use List<string> instead (which internally stores its items in array):

var strList = new List<string> { "1", "2", "3", "5", "6" };
strList.Insert(2, "foo");

If you'll need to convert the list into array, use ToArray extension method:

var strArray = strList.ToArray();

Upvotes: 4

Related Questions