Add new item in existing array
The following console c# example code demonstrate us how can we add an item/element to an existing array programmatically at run time in an console application. .Net framework’s array class has no direct built in method or property to add or append an element with value to array elements collection.
.Net framework’s array object is a fixed size elements collection. so, if we want to add an item to an existing array object, then fist we need to resize array object to allocate available space for new element. Array.resize() method allow us to change the number of elements of a one-dimensional array to the specified new size.
To add a new element to an array object we can set array new size as Array.Length+1. Now, the last element of the array is our newly added empty element. We can set a value for this newly added element as this way Array[Array.Length-1]=”value”. array.Length-1 indicate the last element of an array, because array maintain zero-based index.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Program { static void Main(string[] args) { string[] birds = new string[] { "Pied Monarch", "Crested Jay", "Blue Jay", "European Magpie" }; Console.WriteLine("birds array[" + birds.Length.ToString() + "]........."); foreach (string s in birds) { Console.WriteLine(s ); } Array.Resize(ref birds, birds.Length + 1); birds[birds.Length - 1] = "House Crow"; Console.WriteLine("after added new item birds array[" + birds.Length.ToString() + "]........."); foreach (string s in birds) { Console.WriteLine(s); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | birds array[4]......... Pied Monarch Crested Jay Blue Jay European Magpie after added new item birds array[5]......... Pied Monarch Crested Jay Blue Jay European Magpie House Crow |